3 ms·
Trying to read lodash can (to put it mildly) be difficult. Lots of code reuse. This is probably missing checking for a bunch of corner cases, but this is the g
by jauntywundrkind 3y ago
Trying to read lodash can (to put it mildly) be difficult. Lots of code reuse.
This is probably missing checking for a bunch of corner cases, but this is the general idea:
// quick & dirty Object.groupBy
function groupBy(iterable, callbackFn) {
const out = {}
for(const [key, value] in Object.entries(iterable)) {
const name = callbackFn(value, key)
(out[name] || (out[name] = [])).push(value)
}
return out
}
I literally wrote something very like this yesterday (after checking & finding it only got added to Node 21, and deciding not to pull in a dependency).
Edit: had keyBy impl in here, fixed! Thanks commenters!
- tibbar 3y agoI think `out` should be typed as a map to an array in this case; each iteration should be appending to the corresponding array instead of overwriting the entire entry.
- quonn 3y agoThat‘s closer to keyBy than groupBy.
- moritzwarhier 3y agoOh yes, I agree. I remember me running into the problem of internal dependencies when extracting parts of it into a non-ESM/non-build project some years ago... Like, the internal consistency of the library probably benefits, and with tree-shaking it works reasonably well but it is still a poster example of DRY vs KISS... It has its benefits, but its API surface can be annoying, too. When I encounter it, I often have to think for a second and look at the docs, e.g. some cryptic xor or map function with three parameters, one of which being an optional config object. OTOH, it can be great to have a well-tested implementation at hand for all kinds of higher-order functions, like throttle, debounce etc
- explaininjs 3y agoAaannd… now you have a prototype pollution vulnerability :) Object.from(null), always.