Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve groupBy #2532

Merged
merged 7 commits into from
Nov 23, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 35 additions & 6 deletions src/internal/group-by.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TValue>(
values: ReadonlyArray<TValue>,
keyFunction: (value: TValue) => string | number
): Record<string, TValue[]> {
const result: Record<string, 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 = keyFunction(value);
const key = keyMapper(value);
if (result[key] === undefined) {
result[key] = [];
}

result[key].push(value);
result[key].push(valueMapper(value));
}

return result;
Expand Down