aboutsummaryrefslogtreecommitdiff
path: root/src/internal
diff options
context:
space:
mode:
authorST-DDT <[email protected]>2023-11-23 20:10:07 +0100
committerGitHub <[email protected]>2023-11-23 19:10:07 +0000
commitc2b952347e1f952cf379807a3c456fed65075d11 (patch)
treea7b813f499c4dbf8420cf547b4b412993503b375 /src/internal
parent9b00fe9f7353df50c67966141a5f024ec9b95208 (diff)
downloadfaker-c2b952347e1f952cf379807a3c456fed65075d11.tar.xz
faker-c2b952347e1f952cf379807a3c456fed65075d11.zip
refactor: improve groupBy (#2532)
Diffstat (limited to 'src/internal')
-rw-r--r--src/internal/group-by.ts41
1 files changed, 35 insertions, 6 deletions
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<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;