File size: 788 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
24
25
26
27
28
29
30
31
32
import { findById } from '@/utils/array/findById';

export const upsertPropertiesOfItemIntoArrayOfObjectsComparingId = <
  T extends { id: string },
>(
  arrayToUpsertInto: T[],
  propertiesToUpsert: Partial<T> & { id: string },
): T[] => {
  const alreadyExistingItemIndex = arrayToUpsertInto.findIndex(
    findById(propertiesToUpsert.id),
  );

  const shouldReplaceItem = alreadyExistingItemIndex > -1;

  if (shouldReplaceItem) {
    const newArray = [...arrayToUpsertInto];

    const itemToUpsert = {
      ...arrayToUpsertInto[alreadyExistingItemIndex],
      ...propertiesToUpsert,
    } as T;

    newArray.splice(alreadyExistingItemIndex, 1, itemToUpsert);

    return newArray;
  } else {
    return arrayToUpsertInto.concat({
      ...propertiesToUpsert,
    } as T);
  }
};