Skip to content

Commit

Permalink
feat: let counting accept any iterable
Browse files Browse the repository at this point in the history
+71 bytes
  • Loading branch information
aleclarson committed Jul 7, 2024
1 parent c1df00d commit 0775a84
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions src/array/counting.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -7,19 +9,17 @@
* // { even: 2, odd: 2 }
* ```
*/
export function counting<T, TId extends string | number | symbol>(
array: readonly T[],
identity: (item: T) => TId,
): Record<TId, number> {
if (!array) {
return {} as Record<TId, number>
export function counting<T extends object, K extends keyof any>(
iterable: T,
identity: (item: ToIterableItem<T>) => K,
): Record<K, number> {
if (!iterable) {
return {} as Record<K, number>
}
return array.reduce(
(acc, item) => {
const id = identity(item)
acc[id] = (acc[id] ?? 0) + 1
return acc
},
{} as Record<TId, number>,
)
const counts = {} as Record<K, number>
for (const item of toIterable(iterable)) {
const id = identity(item)
counts[id] = (counts[id] ?? 0) + 1
}
return counts
}

0 comments on commit 0775a84

Please sign in to comment.