Skip to content

Instantly share code, notes, and snippets.

@techieshark
Created February 22, 2019 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techieshark/122bca5dac8ed817f5223411bff2e6f4 to your computer and use it in GitHub Desktop.
Save techieshark/122bca5dac8ed817f5223411bff2e6f4 to your computer and use it in GitHub Desktop.
simple pick.js implementation
// @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;
}
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