Add packages/common/src/indexBy.ts

This commit is contained in:
Jerko Steiner 2019-03-20 12:37:05 +05:00
parent 7a0d44abe4
commit 5317187a45
4 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,17 @@
module.exports = {
roots: [
'<rootDir>/src'
],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|\\.(test|spec))\\.tsx?$',
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx'
],
setupFiles: ['<rootDir>/jest.setup.js'],
verbose: false
}

View File

View File

@ -0,0 +1,28 @@
import {indexBy} from './indexBy'
describe('indexBy', () => {
const items = [{
id: 10,
name: 'one',
value: true,
}, {
id: 20,
name: 'two',
value: false,
}]
it('indexes objects by string property', () => {
expect(indexBy(items, 'id')).toEqual({
10: items[0],
20: items[1],
})
})
it('indexes objects by numeric property', () => {
expect(indexBy(items, 'name')).toEqual({
one: items[0],
two: items[1],
})
})
})

View File

@ -0,0 +1,9 @@
export function indexBy<T extends object, K extends keyof T>(
items: T[],
key: T[K] extends string | number ? K : never,
) {
return items.reduce((obj, item) => {
obj[String(item[key])] = item
return obj
}, {} as {[k: string]: T})
}