Skip to content

Commit

Permalink
feat(groupBy): Accept number and symbol keys in groupBy
Browse files Browse the repository at this point in the history
  • Loading branch information
mass2527 committed Jun 30, 2024
1 parent fc1a8e6 commit 517401f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
22 changes: 21 additions & 1 deletion src/array/groupBy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('groupBy', () => {
{ score: 1, name: 'Joe' },
];

const result = groupBy(array, item => item.score.toString());
const result = groupBy(array, item => item.score);

expect(result).toEqual({
'1': [
Expand All @@ -62,6 +62,26 @@ describe('groupBy', () => {
});
});

it('should group elements by a symbol key', () => {
const TYPE_A = Symbol();
const TYPE_B = Symbol();
const array = [
{ type: TYPE_A, score: 1, name: 'John' },
{ type: TYPE_A, score: 2, name: 'Jane' },
{ type: TYPE_B, score: 1, name: 'Joe' },
];

const result = groupBy(array, item => item.type);

expect(result).toEqual({
[TYPE_A]: [
{ type: TYPE_A, score: 1, name: 'John' },
{ type: TYPE_A, score: 2, name: 'Jane' },
],
[TYPE_B]: [{ type: TYPE_B, score: 1, name: 'Joe' }],
});
});

it('should handle duplicate keys correctly', () => {
const array = [
{ category: 'fruit', name: 'apple' },
Expand Down
2 changes: 1 addition & 1 deletion src/array/groupBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* // ]
* // }
*/
export function groupBy<T, K extends string>(arr: readonly T[], getKeyFromItem: (item: T) => K): Record<K, T[]> {
export function groupBy<T, K extends PropertyKey>(arr: readonly T[], getKeyFromItem: (item: T) => K): Record<K, T[]> {
const result = {} as Record<K, T[]>;

for (const item of arr) {
Expand Down

0 comments on commit 517401f

Please sign in to comment.