feat: add groupByKey utility

This commit is contained in:
Ilia Mashkov
2026-04-24 09:18:18 +03:00
parent d89dc2ee70
commit fce4672218
3 changed files with 74 additions and 0 deletions
+54
View File
@@ -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' }],
});
});
});
});