Suite of AT Protocol TypeScript libraries built on web standards
1export function arrayAgg<T, O>(
2 arr: readonly T[],
3 cmp: (a: T, b: T) => boolean,
4 agg: (items: [T, ...T[]]) => O,
5): O[] {
6 if (arr.length === 0) return [];
7
8 const groups: [T, ...T[]][] = [[arr[0]]];
9 const skipped = Array<undefined | boolean>(arr.length);
10
11 outer: for (let i = 1; i < arr.length; i++) {
12 if (skipped[i]) continue;
13 const item = arr[i];
14 for (let j = 0; j < groups.length; j++) {
15 if (cmp(item, groups[j][0])) {
16 groups[j].push(item);
17 skipped[i] = true;
18 continue outer;
19 }
20 }
21 groups.push([item]);
22 }
23
24 return groups.map(agg);
25}