Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider groupBy generic operation #3

Open
souenzzo opened this issue Aug 28, 2020 · 4 comments
Open

Consider groupBy generic operation #3

souenzzo opened this issue Aug 28, 2020 · 4 comments

Comments

@souenzzo
Copy link

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 (?!)

@joaolucasl
Copy link
Owner

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 :)

@souenzzo
Copy link
Author

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()))

@Dagur
Copy link

Dagur commented Dec 13, 2023

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)

@bergus
Copy link

bergus commented Dec 13, 2023

@Dagur

const { even, odd } = Object.groupBy([1, 2, 3], x => x % 2 ? 'odd' : 'even')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants