Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Last active August 18, 2020 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save friendlyanon/c3e80556da6d6e8dc738b7b53b69ab92 to your computer and use it in GitHub Desktop.
Save friendlyanon/c3e80556da6d6e8dc738b7b53b69ab92 to your computer and use it in GitHub Desktop.
export type AtLeastOne<T> = [T, ...T[]];
export function groupByUsing<V, K extends keyof V, U>(
iterable: Iterable<V>,
key: K | ((value: V, index: number) => V[K]),
callback: (value: V, index: number) => U,
): Map<V[K], AtLeastOne<U>> {
const mapper = typeof key !== "function" ? (v: V) => v[key] : key;
const map = new Map<V[K], AtLeastOne<U>>();
let i = 0;
for (const value of iterable) {
const mappedKey = mapper(value, i);
const mappedValue = callback(value, i++);
const group = map.get(mappedKey);
if (group == null) {
map.set(mappedKey, [mappedValue]);
} else {
group.push(mappedValue);
}
}
return map;
}
export const groupBy = <V, K extends keyof V>(
iterable: Iterable<V>,
key: K | ((value: V, index: number) => V[K]),
) => groupByUsing(iterable, key, v => v);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment