-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: add-map-array-to-key-value-map-function
- Loading branch information
=
committed
May 15, 2024
1 parent
3a01fad
commit 4577c2c
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
packages/common/src/map-array-to-key-value-map.function.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' }); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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])); | ||
} |