Skip to content

Commit

Permalink
feat(keyBy): Accept number and symbol keys in keyBy (toss#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
mass2527 authored Jun 30, 2024
1 parent fc1a8e6 commit a9e317b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
30 changes: 26 additions & 4 deletions src/array/keyBy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,39 @@ import { describe, expect, it } from 'vitest';
import { keyBy } from './keyBy';

describe('keyBy', () => {
it('should return the mapped object by given key', () => {
it('should map each element of an array by string key', () => {
const people = [
{ name: 'mike', age: 20 },
{ name: 'jake', age: 30 },
];

const result = keyBy(people, person => person.age.toString());
const result = keyBy(people, person => person.name);
expect(result).toEqual({ mike: { name: 'mike', age: 20 }, jake: { name: 'jake', age: 30 } });
});

it('should map each element of an array by number key', () => {
const people = [
{ name: 'mike', age: 20 },
{ name: 'jake', age: 30 },
];

const result = keyBy(people, person => person.age);
expect(result).toEqual({ 20: { name: 'mike', age: 20 }, 30: { name: 'jake', age: 30 } });
});

it('should map each element of an array by symbol key', () => {
const id1 = Symbol('id');
const id2 = Symbol('id');
const people = [
{ id: id1, name: 'mike', age: 20 },
{ id: id2, name: 'jake', age: 30 },
];

const result2 = keyBy(people, person => person.name);
expect(result2).toEqual({ mike: { name: 'mike', age: 20 }, jake: { name: 'jake', age: 30 } });
const result = keyBy(people, person => person.id);
expect(result).toEqual({
[id1]: { id: id1, name: 'mike', age: 20 },
[id2]: { id: id2, name: 'jake', age: 30 },
});
});

it('should overwrite the value when encountering the same key', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/array/keyBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
* // vegetable: { category: 'vegetable', name: 'carrot' }
* // }
*/
export function keyBy<T, K extends string>(arr: readonly T[], getKeyFromItem: (item: T) => K): Record<K, T> {
export function keyBy<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 a9e317b

Please sign in to comment.