All files / object pick.ts

100% Statements 10/10
50% Branches 1/2
100% Functions 3/3
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41                    3x 5x 5x       1x 1x   1x 1x             1x     1x       1x            
/**
 * pick keys and omit others in the object
 *
 * @param obj the destination object
 * @param keys the keys to pick
 * @returns object
 *
 * {@link https://lodash.com/docs#pick}
 */
export function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  return keys.reduce((acc, key) => {
    acc[key] = obj[key]
    return acc
  }, {} as Pick<T, K>)
}
 
Eif (import.meta.vitest) {
  const { test, expect } = import.meta.vitest
 
  test('pick', () => {
    const obj = {
      a: 1,
      b: '2',
      c: false,
      d: null,
    }
 
    expect(pick(obj, ['a'])).toEqual({
      a: 1,
    })
    expect(pick(obj, ['b', 'd'])).toEqual({
      b: '2',
      d: null,
    })
    expect(pick(obj, ['d', 'a'])).toEqual({
      a: 1,
      d: null,
    })
  })
}