Add packages/common/src/indexBy.ts
This commit is contained in:
parent
7a0d44abe4
commit
5317187a45
17
packages/common/jest.config.js
Normal file
17
packages/common/jest.config.js
Normal 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
|
||||
}
|
||||
0
packages/common/jest.setup.js
Normal file
0
packages/common/jest.setup.js
Normal file
28
packages/common/src/indexBy.test.ts
Normal file
28
packages/common/src/indexBy.test.ts
Normal 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],
|
||||
})
|
||||
})
|
||||
})
|
||||
9
packages/common/src/indexBy.ts
Normal file
9
packages/common/src/indexBy.ts
Normal 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})
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user