Created
June 29, 2024 02:45
-
-
Save forivall/587743583df3acecb0097463e35fd409 to your computer and use it in GitHub Desktop.
Map.groupBy minimal ponyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This is equivalent to Map.groupBy; replace this function with Map.groupBy in Node 21+ */ | |
function mapGroupBy<T, K>(array: T[], iteratee: (value: T, index: number, array: T[]) => K) { | |
return array.reduce((result, value, index, array) => { | |
const key = iteratee(value, index, array); | |
const group = result.get(key); | |
if (group) { | |
group.push(value); | |
} else { | |
result.set(key, [value]); | |
} | |
return result; | |
}, new Map<K, T[]>()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment