From c2b952347e1f952cf379807a3c456fed65075d11 Mon Sep 17 00:00:00 2001 From: ST-DDT Date: Thu, 23 Nov 2023 20:10:07 +0100 Subject: refactor: improve groupBy (#2532) --- src/internal/group-by.ts | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/internal/group-by.ts b/src/internal/group-by.ts index ff3242c9..1fc86e8c 100644 --- a/src/internal/group-by.ts +++ b/src/internal/group-by.ts @@ -4,21 +4,50 @@ * @internal * * @param values The values to group. - * @param keyFunction The function to get the key from the value. + * @param keyMapper The function to get the key from the value. */ export function groupBy( values: ReadonlyArray, - keyFunction: (value: TValue) => string | number -): Record { - const result: Record = {}; + keyMapper: (value: TValue) => string | number +): Record; +/** + * Groups the values by the key function and maps the values. + * + * @internal + * + * @param values The values to group. + * @param keyMapper The function to get the key from the value. + * @param valueMapper The function to get the value from the value. + */ +export function groupBy( + values: ReadonlyArray, + keyMapper: (value: TOriginalValue) => string | number, + valueMapper: (value: TOriginalValue) => TMappedValue +): Record; +/** + * Groups the values by the key function and maps the values. + * + * @internal + * + * @param values The values to group. + * @param keyMapper The function to get the key from the value. + * @param valueMapper The function to map the value. + */ +export function groupBy( + values: ReadonlyArray, + keyMapper: (value: TOriginalValue) => string | number, + valueMapper: (value: TOriginalValue) => TMappedValue = (value) => + value as unknown as TMappedValue +): Record { + const result: Record = {}; for (const value of values) { - const key = keyFunction(value); + const key = keyMapper(value); if (result[key] === undefined) { result[key] = []; } - result[key].push(value); + result[key].push(valueMapper(value)); } return result; -- cgit v1.2.3