Last active
August 18, 2020 10:42
-
-
Save friendlyanon/c3e80556da6d6e8dc738b7b53b69ab92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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