20 lines
375 B
JavaScript
20 lines
375 B
JavaScript
/**
|
|
* Groups array items into a Map, given a function to produce grouping key.
|
|
*/
|
|
export function groupBy(list, keyFn) {
|
|
const result = new Map();
|
|
|
|
for (const item of list) {
|
|
const key = keyFn(item);
|
|
const group = result.get(key);
|
|
|
|
if (group === undefined) {
|
|
result.set(key, [item]);
|
|
} else {
|
|
group.push(item);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|