feat(collections/group_by): accept iterable input, add index param to callback (#3390)

This commit is contained in:
Jesse Jackson 2023-05-18 22:59:12 -05:00 committed by GitHub
parent 1000a6bd57
commit 9e21d9d047
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 5 deletions

View File

@ -28,14 +28,15 @@
* ```
*/
export function groupBy<T, K extends string>(
array: readonly T[],
selector: (el: T) => K,
iterable: Iterable<T>,
selector: (element: T, index: number) => K,
): Partial<Record<K, T[]>> {
const ret: Partial<Record<K, T[]>> = {};
let i = 0;
for (const element of array) {
const key = selector(element);
const arr = ret[key] ??= [] as T[];
for (const element of iterable) {
const key = selector(element, i++);
const arr: T[] = ret[key] ??= [];
arr.push(element);
}

View File

@ -85,3 +85,31 @@ Deno.test({
);
},
});
Deno.test({
name: "[collections/groupBy] callback index",
fn() {
const actual = groupBy(
["a", "b", "c", "d"],
(_, i) => i % 2 === 0 ? "even" : "odd",
);
const expected = { even: ["a", "c"], odd: ["b", "d"] };
assertEquals(actual, expected);
},
});
Deno.test({
name: "[collections/groupBy] iterable input",
fn() {
function* count(): Generator<number, void> {
for (let i = 0; i < 5; i += 1) yield i;
}
const actual = groupBy(count(), (n) => n % 2 === 0 ? "even" : "odd");
const expected = { even: [0, 2, 4], odd: [1, 3] };
assertEquals(actual, expected);
},
});