Skip to content

Commit

Permalink
feat: let group accept any iterable
Browse files Browse the repository at this point in the history
Note: This increases `group`‘s minified bytes by 100%
  • Loading branch information
aleclarson committed Jul 7, 2024
1 parent 89f6c7a commit db107f1
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/array/group.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { reduceIterable, type ToIterableItem } from 'radashi'

/**
* Sorts an `array` of items into groups. The return value is a map
* where the keys are the group IDs the given `getGroupId` function
Expand All @@ -8,19 +10,18 @@
* // { even: [2], odd: [1, 3, 4] }
* ```
*/
export function group<T, Key extends string | number | symbol>(
array: readonly T[],
getGroupId: (item: T) => Key,
): { [K in Key]?: T[] } {
return array.reduce(
export function group<T extends object, Key extends string | number | symbol>(
iterable: T,
getGroupId: (item: ToIterableItem<T>) => Key,
): { [K in Key]?: ToIterableItem<T>[] } {
return reduceIterable(
iterable,
(acc, item) => {
const groupId = getGroupId(item)
if (!acc[groupId]) {
acc[groupId] = []
}
acc[groupId] ??= []
acc[groupId].push(item)
return acc
},
{} as Record<Key, T[]>,
{} as Record<Key, ToIterableItem<T>[]>,
)
}

0 comments on commit db107f1

Please sign in to comment.