Created
May 26, 2020 16:31
-
-
Save friendlyanon/9f396e735da4140327db6a909285cf8c to your computer and use it in GitHub Desktop.
This file contains 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
export const groupByUsing = (iterable, key, callback) => { | |
const mapper = typeof key !== "function" ? x => x[key] : key; | |
const map = new Map(); | |
let i = -1; | |
for (const value of iterable) { | |
const mappedKey = mapper(value, ++i, key); | |
const mappedValue = callback(value, i, key); | |
const group = map.get(mappedKey); | |
if (group == null) { | |
map.set(mappedKey, [mappedValue]); | |
} else { | |
group.push(mappedValue); | |
} | |
} | |
return map; | |
}; | |
export const groupBy = (iterable, key) => groupByUsing(iterable, key, x => x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment