From 8542ef30bd4eda3d9f04db2c4a79abf0369d57c3 Mon Sep 17 00:00:00 2001 From: ST-DDT Date: Tue, 7 Nov 2023 17:26:27 +0100 Subject: infra(unicorn): no-array-reduce (#2479) --- src/internal/group-by.ts | 25 +++++++++++++++++++++++++ src/modules/word/filter-word-list-by-length.ts | 10 ++-------- 2 files changed, 27 insertions(+), 8 deletions(-) create mode 100644 src/internal/group-by.ts (limited to 'src') diff --git a/src/internal/group-by.ts b/src/internal/group-by.ts new file mode 100644 index 00000000..ff3242c9 --- /dev/null +++ b/src/internal/group-by.ts @@ -0,0 +1,25 @@ +/** + * Groups the values by the key function. + * + * @internal + * + * @param values The values to group. + * @param keyFunction The function to get the key from the value. + */ +export function groupBy( + values: ReadonlyArray, + keyFunction: (value: TValue) => string | number +): Record { + const result: Record = {}; + + for (const value of values) { + const key = keyFunction(value); + if (result[key] === undefined) { + result[key] = []; + } + + result[key].push(value); + } + + return result; +} diff --git a/src/modules/word/filter-word-list-by-length.ts b/src/modules/word/filter-word-list-by-length.ts index 60c6fae9..f3fcd5ab 100644 --- a/src/modules/word/filter-word-list-by-length.ts +++ b/src/modules/word/filter-word-list-by-length.ts @@ -1,4 +1,5 @@ import { FakerError } from '../../errors/faker-error'; +import { groupBy } from '../../internal/group-by'; /** * The error handling strategies for the `filterWordListByLength` function. @@ -13,14 +14,7 @@ const STRATEGIES = { wordList: ReadonlyArray, length: { min: number; max: number } ): string[] => { - const wordsByLength = wordList.reduce>( - (data, word) => { - (data[word.length] = data[word.length] ?? []).push(word); - return data; - }, - {} - ); - + const wordsByLength = groupBy(wordList, (word) => word.length); const lengths = Object.keys(wordsByLength).map(Number); const min = Math.min(...lengths); const max = Math.max(...lengths); -- cgit v1.2.3