/ src / utils / array.ts
array.ts
 1  /**
 2   * Split an array into two groups based on the result {@linkcode predicate}
 3   *
 4   * Items for which {@linkcode predicate} returns `true` will be in the "left"
 5   * result, and the others in the "right" one
 6   */
 7  export function partition<T>(
 8      input: Array<T>,
 9      predicate: (element: T) => boolean,
10  ): [Array<T>, Array<T>] {
11      const left: Array<T> = [];
12      const right: Array<T> = [];
13  
14      for (const element of input) {
15          if (predicate(element)) {
16              left.push(element);
17          } else {
18              right.push(element);
19          }
20      }
21  
22      return [left, right];
23  }
24  
25  /**
26   * Deduplicate the elements of {@linkcode items} by their `id` property
27   */
28  export function uniqueById<T extends { id: string }>(items: T[]): T[] {
29      const entries = items.map((item) => [item.id, item] as const);
30      const mapById = new Map<string, T>(entries);
31  
32      return Array.from(mapById.values());
33  }