feat: add groupByKey utility
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import { groupByKey } from './groupByKey';
|
||||
|
||||
describe('groupByKey', () => {
|
||||
describe('basic grouping', () => {
|
||||
it('groups items by a string key', () => {
|
||||
const items = [
|
||||
{ category: 'Frontend', name: 'React' },
|
||||
{ category: 'Backend', name: 'Node' },
|
||||
{ category: 'Frontend', name: 'Vue' },
|
||||
];
|
||||
expect(groupByKey(items, 'category')).toEqual({
|
||||
Frontend: [
|
||||
{ category: 'Frontend', name: 'React' },
|
||||
{ category: 'Frontend', name: 'Vue' },
|
||||
],
|
||||
Backend: [{ category: 'Backend', name: 'Node' }],
|
||||
});
|
||||
});
|
||||
|
||||
it('preserves insertion order within each group', () => {
|
||||
const items = [
|
||||
{ category: 'A', order: 1 },
|
||||
{ category: 'A', order: 2 },
|
||||
];
|
||||
expect(groupByKey(items, 'category')['A']).toEqual([
|
||||
{ category: 'A', order: 1 },
|
||||
{ category: 'A', order: 2 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('returns empty object for empty array', () => {
|
||||
expect(groupByKey<{ category: string }>([], 'category')).toEqual({});
|
||||
});
|
||||
|
||||
it('handles all items in same group', () => {
|
||||
const items = [
|
||||
{ type: 'X', id: 1 },
|
||||
{ type: 'X', id: 2 },
|
||||
];
|
||||
const result = groupByKey(items, 'type');
|
||||
expect(Object.keys(result)).toHaveLength(1);
|
||||
expect(result['X']).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('handles single item', () => {
|
||||
const items = [{ category: 'Only', name: 'One' }];
|
||||
expect(groupByKey(items, 'category')).toEqual({
|
||||
Only: [{ category: 'Only', name: 'One' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user