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

A nice typesafe groupBy / partition function #525

Open
basarat opened this issue Oct 4, 2019 · 1 comment
Open

A nice typesafe groupBy / partition function #525

basarat opened this issue Oct 4, 2019 · 1 comment

Comments

@basarat
Copy link
Owner

basarat commented Oct 4, 2019

https://twitter.com/SeaRyanC/status/1179816663199277056 🌹

image

image

@0xdevalias
Copy link

Extracted for easier copy/paste:

function partition<T, U extends string>(
  arr: ReadonlyArray<T>,
  sorter: (el: T) => U
) {
  const res = {} as { [K in U]: T[] | undefined };
  for (const el of arr) {
    const key = sorter(el);
    const target: T[] = res[key] ?? (res[key] = []);
    target.push(el);
  }
  return res;
}

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

2 participants