Add createFilterProps

This commit is contained in:
Jerko Steiner 2019-04-03 18:02:36 +08:00
parent 91f47653bf
commit 831001a9c5
3 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,35 @@
import {createFilterProps} from './filterProps'
interface IEntity {
readonly id: number
}
interface IPerson {
readonly firstName: string
readonly lastName: string
}
interface IPersonEntity extends IEntity, IPerson {}
describe('filterProps', () => {
const p: IPersonEntity = {
id: 1,
firstName: 'John',
lastName: 'Smith',
}
const filterProps = createFilterProps<IPerson>({
firstName: true,
lastName: true,
})
it('picks only relevant props', () => {
const person = filterProps(p)
expect(person).toEqual({
firstName: 'John',
lastName: 'Smith',
})
})
})

View File

@ -0,0 +1,8 @@
export function createFilterProps<T>(schema: Record<keyof T & string, true>) {
return function filterProps<U extends T>(item: U): T {
return Object.keys(schema).reduce((obj: T, key) => {
obj[key as keyof T] = item[key as keyof T]
return obj
}, {} as T)
}
}

View File

@ -10,6 +10,7 @@ export * from './IUser'
export * from './IUserInTeam' export * from './IUserInTeam'
export * from './IUserTeam' export * from './IUserTeam'
export * from './URLFormatter' export * from './URLFormatter'
export * from './filterProps'
export * from './indexBy' export * from './indexBy'
export * from './types' export * from './types'
export * from './without' export * from './without'