|
1
|
/** |
|
2
|
* Computes the difference between a current set of values and a new set of value IDs. |
|
3
|
* Handles both regular arrays and MikroORM collections. |
|
4
|
* |
|
5
|
* @param currentValues - Current values (array or MikroORM collection with toArray method) |
|
6
|
* @param newValueIds - Array of new value IDs to compare against |
|
7
|
* @returns Object with arrays of value IDs to remove and add |
|
8
|
* |
|
9
|
* @example |
|
10
|
* ```ts |
|
11
|
* const currentValues = [{ id: "1" }, { id: "2" }, { id: "3" }] |
|
12
|
* const newValueIds = ["2", "3", "4"] |
|
13
|
* const diff = computeSetDifference(currentValues, newValueIds) |
|
14
|
* // Result: { toRemove: ["1"], toAdd: ["4"] } |
|
15
|
* ``` |
|
16
|
*/ |
|
17
|
export function computeSetDifference( |
|
18
|
currentValues: { id: string }[] | { toArray?(): { id: string }[] } | null, |
|
19
|
newValueIds: string[] |
|
20
|
): { toRemove: string[]; toAdd: string[] } { |
|
21
|
const normalized: { id: string }[] = Array.isArray(currentValues) |
|
22
|
? currentValues |
|
23
|
: (currentValues as any)?.toArray?.() ?? [] |
|
24
|
|
|
25
|
const currentSet = new Set<string>(normalized.map((v) => v.id)) |
|
26
|
const newSet = new Set<string>(newValueIds) |
|
27
|
|
|
28
|
return { |
|
29
|
toRemove: Array.from(currentSet).filter((id) => !newSet.has(id)), |
|
30
|
toAdd: Array.from(newSet).filter((id) => !currentSet.has(id)), |
|
31
|
} |
|
32
|
} |