Spaces:
Build error
Build error
File size: 577 Bytes
d9494a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import { findById } from '@/utils/array/findById';
export const upsertIntoArrayOfObjectsComparingId = <T extends { id: string }>(
arrayToUpsertInto: T[],
itemToUpsert: T,
): T[] => {
const alreadyExistingItemIndex = arrayToUpsertInto.findIndex(
findById(itemToUpsert.id),
);
const shouldReplaceItem = alreadyExistingItemIndex > -1;
if (shouldReplaceItem) {
const newArray = [...arrayToUpsertInto];
newArray.splice(alreadyExistingItemIndex, 1, itemToUpsert);
return newArray;
} else {
return arrayToUpsertInto.concat(itemToUpsert);
}
};
|