Skip to content

Commit 9b00c16

Browse files
committed
Implement reduceBy helper
1 parent 7491947 commit 9b00c16

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/helpers/array_helpers.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
arrayWithout,
2323
arrayWithoutIndexes,
2424
arrayZip,
25+
reduceBy,
2526
} from './array_helpers';
2627

2728
describe('Array helpers', () => {
@@ -256,6 +257,34 @@ describe('Array helpers', () => {
256257
expect(arrayFrom(null, true)).toEqual([]);
257258
});
258259

260+
it('reduces by key', () => {
261+
const items = [
262+
{ id: '1', name: 'Alice' },
263+
{ id: '2', name: 'Bob' },
264+
];
265+
266+
const result = reduceBy(items, 'id');
267+
268+
expect(result).toEqual({
269+
1: { id: '1', name: 'Alice' },
270+
2: { id: '2', name: 'Bob' },
271+
});
272+
});
273+
274+
it('reduces by key with projection', () => {
275+
const items = [
276+
{ id: '1', name: 'Alice' },
277+
{ id: '2', name: 'Bob' },
278+
];
279+
280+
const result = reduceBy(items, 'id', (item) => item.name);
281+
282+
expect(result).toEqual({
283+
1: 'Alice',
284+
2: 'Bob',
285+
});
286+
});
287+
259288
});
260289

261290
let enabled: boolean | undefined;

src/helpers/array_helpers.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,24 @@ export function arrayFrom<T>(value: T, ignoreEmptyValues: boolean = false): Arra
310310
export function range(length: number): number[] {
311311
return Array.from({ length }, (_, item) => item);
312312
}
313+
314+
export function reduceBy<TItem, TKey extends keyof TItem, TProjection>(
315+
items: TItem[],
316+
key: TKey,
317+
project: (item: TItem) => TProjection
318+
): Partial<Record<string, TProjection>>;
319+
export function reduceBy<TItem, TKey extends keyof TItem>(items: TItem[], key: TKey): Partial<Record<string, TItem>>;
320+
export function reduceBy<TItem, TKey extends keyof TItem, TProjection>(
321+
items: TItem[],
322+
key: TKey,
323+
project?: (item: TItem) => TProjection,
324+
): Partial<Record<string, TProjection>> {
325+
return items.reduce(
326+
(acc, item) => {
327+
acc[toString(item[key])] = project ? project(item) : (item as unknown as TProjection);
328+
329+
return acc;
330+
},
331+
{} as Partial<Record<string, TProjection>>,
332+
);
333+
}

0 commit comments

Comments
 (0)