typescript-book icon indicating copy to clipboard operation
typescript-book copied to clipboard

A nice typesafe groupBy / partition function

Open basarat opened this issue 6 years ago • 1 comments

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

image

image

basarat avatar Oct 04 '19 05:10 basarat

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;
}

0xdevalias avatar Dec 04 '24 04:12 0xdevalias