proposal-array-prototype-partition
proposal-array-prototype-partition copied to clipboard
Consider `groupBy` generic operation
It's a bit more generic operation "partition"
let groupBy = (f, coll) => {
let rf = (acc, el) => {
let id = f(el);
acc[id] = [... (acc[id] || []), el]
return acc
}
return coll.reduce(rf , {})
}
Can be used as partition
as:
let {false: f, true: t} = groupBy( x => x == 2 , [1,2,3])
Maybe should we accumulate over an actual Map
allowing f
return any object (?!)
Good one! Will give it a little more thought and search if there's an already existing proposal.
My only concern with it is that it returns an Object
instead of an array, so it kind of deviates from the Array
stuff. But I like the idea nonetheless :)
A example supporting both Objects and Maps
Array.prototype.groupBy = function (f, init = {}) {
let rfMap = (acc, el) => {
let id = f(el);
let els = [... acc.get(id) || [], el];
return acc.set(id, els);
}
let rfObject = (acc, el) => {
let id = f(el);
let els = [... (acc[id] || []), el];
acc[id] = els;
return acc;
}
return this.reduce(init instanceof Map ? rfMap : rfObject , init)
}
let {true: t} = [1,2,3].groupBy(x => x == 2)
console.log(t , [1,2,3].groupBy(x => x == 2, new Map()))
groupBy is great but this
const [even, odd] = [1,2,3].partition( x => x % 2);
is much nicer than
const { 0: even, 1: odd } = Object.groupBy([1,2,3], x => x % 2)
@Dagur
const { even, odd } = Object.groupBy([1, 2, 3], x => x % 2 ? 'odd' : 'even')