added Map.groupBy

This commit is contained in:
wea_ondara
2023-09-26 16:42:02 +02:00
parent 089ac33d93
commit 641a4425aa
4 changed files with 20 additions and 0 deletions

11
src/util.ts Normal file
View File

@@ -0,0 +1,11 @@
export default function groupBy<K, V>(arr: V[], fn: (v: V) => K): Map<K, V[]> {
const map = new Map<K, V[]>();
arr.forEach(e => {
const key = fn(e);
if (!map.has(key)) {
map.set(key, [] as V[]);
}
map.get(key)!.push(e);
});
return map;
}