Skip to content

Instantly share code, notes, and snippets.

@zoxon
Last active March 3, 2022 10:09
Show Gist options
  • Save zoxon/58a6a26b6aa4db9a3f898311b0450799 to your computer and use it in GitHub Desktop.
Save zoxon/58a6a26b6aa4db9a3f898311b0450799 to your computer and use it in GitHub Desktop.
Converts array of objects to object with key
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' }
})
})
})
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