From 4577c2c6ac3033e6e901a03acdc9fc313ebd95fb Mon Sep 17 00:00:00 2001 From: = <=> Date: Wed, 15 May 2024 19:21:51 +0300 Subject: [PATCH] feature: add-map-array-to-key-value-map-function --- ...ap-array-to-key-value-map.function.spec.ts | 33 +++++++++++++++++++ .../map-array-to-key-value-map.function.ts | 3 ++ 2 files changed, 36 insertions(+) create mode 100644 packages/common/src/map-array-to-key-value-map.function.spec.ts create mode 100644 packages/common/src/map-array-to-key-value-map.function.ts diff --git a/packages/common/src/map-array-to-key-value-map.function.spec.ts b/packages/common/src/map-array-to-key-value-map.function.spec.ts new file mode 100644 index 0000000..1eed929 --- /dev/null +++ b/packages/common/src/map-array-to-key-value-map.function.spec.ts @@ -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 = 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 = 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 = 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' }); + }); +}); diff --git a/packages/common/src/map-array-to-key-value-map.function.ts b/packages/common/src/map-array-to-key-value-map.function.ts new file mode 100644 index 0000000..e97b40b --- /dev/null +++ b/packages/common/src/map-array-to-key-value-map.function.ts @@ -0,0 +1,3 @@ +export function mapArrayToKeyValueMap(array: T[], key: Key): Map { + return new Map(array.map((item: T) => [item[key], item])); +}