Last active
March 3, 2022 10:09
-
-
Save zoxon/58a6a26b6aa4db9a3f898311b0450799 to your computer and use it in GitHub Desktop.
Converts array of objects to object with key
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
describe('arrayToKeyedObject', () => { | |
it('should return empty object if array are empty', () => { | |
type GenericItems = { code: string } | |
const items: GenericItems[] = [] | |
const result = arrayToKeyedObject(items, (item) => item.code) | |
expect(result).toEqual({}) | |
}) | |
it('should return keyed object', () => { | |
const items = [{ code: 'one' }, { code: 'two' }] | |
const result = arrayToKeyedObject(items, (item) => item?.code) | |
expect(result).toEqual({ | |
one: { code: 'one' }, | |
two: { code: 'two' } | |
}) | |
}) | |
}) |
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
function arrayToKeyedObject<T, K extends string>( | |
array: T[], | |
attributeGetter: (item: T) => K | |
) { | |
if (!Array.isArray(array)) { | |
throw new TypeError('First argument must be an array') | |
} | |
if (!attributeGetter || typeof attributeGetter !== 'function') { | |
throw new TypeError('attributeGetter argument must me a function') | |
} | |
if (array.length === 0) { | |
return {} as Record<K, T> | |
} | |
const map = {} as Record<K, T> | |
for (const value of array) { | |
const key = attributeGetter(value) | |
map[key] = value | |
} | |
return map | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment