|
| 1 | +import { describe, expect, it } from 'vitest'; |
| 2 | + |
| 3 | +import { keyBy } from './keyBy'; |
| 4 | + |
| 5 | +describe('keyBy', () => { |
| 6 | + it('maps items by a string property and overwrites duplicate keys with the last item', () => { |
| 7 | + const items = [ |
| 8 | + { id: 1, slug: 'alpha' }, |
| 9 | + { id: 2, slug: 'beta' }, |
| 10 | + { id: 3, slug: 'alpha' }, |
| 11 | + { id: 4, slug: undefined as string | undefined }, |
| 12 | + ]; |
| 13 | + |
| 14 | + const result = keyBy(items, 'slug'); |
| 15 | + |
| 16 | + expect(result).toEqual({ |
| 17 | + alpha: { id: 3, slug: 'alpha' }, |
| 18 | + beta: { id: 2, slug: 'beta' }, |
| 19 | + }); |
| 20 | + }); |
| 21 | + |
| 22 | + it('handles array properties by assigning the item to each key value', () => { |
| 23 | + const items = [ |
| 24 | + { id: 1, tags: ['red', 'sweet'] }, |
| 25 | + { id: 2, tags: ['sweet', 'tart'] }, |
| 26 | + ]; |
| 27 | + |
| 28 | + const result = keyBy(items, 'tags'); |
| 29 | + |
| 30 | + expect(result).toEqual({ |
| 31 | + red: { id: 1, tags: ['red', 'sweet'] }, |
| 32 | + sweet: { id: 2, tags: ['sweet', 'tart'] }, |
| 33 | + tart: { id: 2, tags: ['sweet', 'tart'] }, |
| 34 | + }); |
| 35 | + }); |
| 36 | + |
| 37 | + it('supports non-string property values by coercing them to string keys', () => { |
| 38 | + const items = [ |
| 39 | + { id: 1, count: 1 }, |
| 40 | + { id: 2, count: 10 }, |
| 41 | + ]; |
| 42 | + |
| 43 | + const result = keyBy(items, 'count'); |
| 44 | + |
| 45 | + expect(result).toEqual({ |
| 46 | + '1': { id: 1, count: 1 }, |
| 47 | + '10': { id: 2, count: 10 }, |
| 48 | + }); |
| 49 | + }); |
| 50 | +}); |
0 commit comments