blob: 1fc86e8c60742a5e3dfe6748cb14a95e23850712 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
/**
* Groups the values by the key function.
*
* @internal
*
* @param values The values to group.
* @param keyMapper The function to get the key from the value.
*/
export function groupBy<TValue>(
values: ReadonlyArray<TValue>,
keyMapper: (value: TValue) => string | number
): Record<string, TValue[]>;
/**
* 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<TOriginalValue, TMappedValue>(
values: ReadonlyArray<TOriginalValue>,
keyMapper: (value: TOriginalValue) => string | number,
valueMapper: (value: TOriginalValue) => TMappedValue
): Record<string, TMappedValue[]>;
/**
* 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<TOriginalValue, TMappedValue>(
values: ReadonlyArray<TOriginalValue>,
keyMapper: (value: TOriginalValue) => string | number,
valueMapper: (value: TOriginalValue) => TMappedValue = (value) =>
value as unknown as TMappedValue
): Record<string, TMappedValue[]> {
const result: Record<string, TMappedValue[]> = {};
for (const value of values) {
const key = keyMapper(value);
if (result[key] === undefined) {
result[key] = [];
}
result[key].push(valueMapper(value));
}
return result;
}
|