Created
February 22, 2019 04:09
-
-
Save techieshark/122bca5dac8ed817f5223411bff2e6f4 to your computer and use it in GitHub Desktop.
simple pick.js implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
/** | |
* Returns new object made of the picked paths. | |
* Native implementation of lodash `pick`. | |
* Shaves 1-2kb off download size: https://bundlephobia.com/result?p=lodash.pick@4.4.0. | |
* @see https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_pick | |
* @see https://lodash.com/docs/#pick | |
* @return {Object} | |
*/ | |
export default function pick(object: Object, paths: Array<string>): Object { | |
const obj = {}; | |
paths.forEach((path) => { | |
if (object[path]) { | |
obj[path] = object[path]; | |
} | |
}); | |
return obj; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pick from './pick'; | |
test('pick() subset', () => { | |
const subset = { a: 1, b: 2 }; | |
const superset = { ...subset, c: 3 }; | |
const picked = pick(superset, Object.keys(subset)); | |
expect(picked).toEqual(subset); | |
}); | |
test('pick() superset', () => { | |
const subset = { a: 1, b: 2 }; | |
const superset = { ...subset, c: 3 }; | |
const picked = pick({ ...subset }, Object.keys(superset)); | |
expect(picked).toEqual(subset); | |
}); | |
test('pick() identity', () => { | |
const set = { a: 1, b: 2 }; | |
const picked = pick({ ...set }, Object.keys(set)); | |
expect(picked).toEqual(set); | |
}); | |
test('pick() no fields of empty object returns empty object', () => { | |
const empty = {}; | |
const picked = pick({ ...empty }, []); | |
expect(picked).toEqual(empty); | |
}); | |
test('pick() missing fields of empty object returns empty object', () => { | |
const missingFields = ['x', 'y', 'z']; | |
const empty = {}; | |
const picked = pick({ ...empty }, missingFields); | |
expect(picked).toEqual(empty); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment