diff --git a/src/array/counting.ts b/src/array/counting.ts index 62cf26af..1564a748 100644 --- a/src/array/counting.ts +++ b/src/array/counting.ts @@ -1,3 +1,5 @@ +import { toIterable, type ToIterableItem } from 'radashi' + /** * Counts the occurrences of each unique value returned by the `identity` * function when applied to each item in the array. @@ -7,19 +9,17 @@ * // { even: 2, odd: 2 } * ``` */ -export function counting( - array: readonly T[], - identity: (item: T) => TId, -): Record { - if (!array) { - return {} as Record +export function counting( + iterable: T, + identity: (item: ToIterableItem) => K, +): Record { + if (!iterable) { + return {} as Record } - return array.reduce( - (acc, item) => { - const id = identity(item) - acc[id] = (acc[id] ?? 0) + 1 - return acc - }, - {} as Record, - ) + const counts = {} as Record + for (const item of toIterable(iterable)) { + const id = identity(item) + counts[id] = (counts[id] ?? 0) + 1 + } + return counts }