Skip to content

Commit

Permalink
feature: add-map-array-to-key-value-map-function
Browse files Browse the repository at this point in the history
  • Loading branch information
= committed May 15, 2024
1 parent 3a01fad commit 4577c2c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
33 changes: 33 additions & 0 deletions packages/common/src/map-array-to-key-value-map.function.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { mapArrayToKeyValueMap } from './map-array-to-key-value-map.function';

describe('mapArrayToKeyValueMap function', () => {
it('should return an empty Map if the input array is empty', () => {
const result: Map<never, never> = mapArrayToKeyValueMap([], 'key');
expect(result.size).toBe(0);
});

it('should correctly map the array elements to key-value pairs in the Map', () => {
const array: { id: number; name: string }[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const result: Map<number, { id: number; name: string }> = mapArrayToKeyValueMap(array, 'id');
expect(result.size).toBe(3);
expect(result.get(1)).toEqual({ id: 1, name: 'Alice' });
expect(result.get(2)).toEqual({ id: 2, name: 'Bob' });
expect(result.get(3)).toEqual({ id: 3, name: 'Charlie' });
});

it('should handle arrays with duplicate keys correctly', () => {
const array: { id: number; name: string }[] = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Charlie' }
];
const result: Map<number, { id: number; name: string }> = mapArrayToKeyValueMap(array, 'id');
expect(result.size).toBe(2);
expect(result.get(1)).toEqual({ id: 1, name: 'Charlie' });
expect(result.get(2)).toEqual({ id: 2, name: 'Bob' });
});
});
3 changes: 3 additions & 0 deletions packages/common/src/map-array-to-key-value-map.function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function mapArrayToKeyValueMap<T extends object, Key extends keyof T>(array: T[], key: Key): Map<T[Key], T> {
return new Map<T[Key], T>(array.map((item: T) => [item[key], item]));
}

0 comments on commit 4577c2c

Please sign in to comment.