fix(collections/group_by): improve type safety (#1880)

This commit is contained in:
Jesse Jackson 2022-02-06 02:32:56 -06:00 committed by GitHub
parent c6d098a2aa
commit 8789df9ea2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -28,22 +28,16 @@
* })
* ```
*/
export function groupBy<T>(
export function groupBy<T, K extends string>(
array: readonly T[],
selector: (el: T) => string,
): Record<string, T[]> {
const ret: Record<string, T[]> = {};
selector: (el: T) => K,
): Partial<Record<K, T[]>> {
const ret: Partial<Record<K, T[]>> = {};
for (const element of array) {
const key = selector(element);
if (ret[key] === undefined) {
ret[key] = [element];
continue;
}
ret[key].push(element);
const arr = ret[key] ??= [] as T[];
arr.push(element);
}
return ret;