element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
31 lines (30 loc) • 1.09 kB
JavaScript
export function insertAndRemoveValues(originalArray, valuesToInsert, indexesToRemove) {
const noOperations = !valuesToInsert.length && !indexesToRemove.length;
const nothingToDoBecauseEmptyArray = originalArray.length
? false
: !valuesToInsert.filter((value) => !!value.index).length;
if (noOperations || nothingToDoBecauseEmptyArray) {
// there's nothing to do
return [...originalArray];
}
const arrayValues = originalArray.map((entry) => {
return [entry];
});
if (!arrayValues.length) {
arrayValues[0] = [];
}
indexesToRemove.forEach((index) => {
if (index >= 0 && index < originalArray.length) {
arrayValues[index] = [];
}
});
valuesToInsert.forEach((valueWrapper) => {
const indexEntry = arrayValues[valueWrapper.index];
if (indexEntry) {
// insert new values before the already existing values
indexEntry.splice(0, 0, ...valueWrapper.values);
}
});
const finalArray = arrayValues.flat();
return finalArray;
}