Skip to content

Commit

Permalink
feat(pluck): pluck method implementation and tests
Browse files Browse the repository at this point in the history
Creates a collection composed of the picked properties from each `object` of the passed collection.
  • Loading branch information
arafatkn committed Dec 26, 2023
1 parent aa18212 commit 71900aa
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/pluck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import map from './map';
import pick from './pick';

/**
* Creates a collection composed of the picked properties from each `object` of the passed collection.
*
* @since 5.0.0
* @category Collection
* @param {Array} collection The collection to iterate over.
* @param {...(string|string[])} [paths] The property paths of each item to pick.
* @returns {Array} Returns the new array.
* @example
*
* const collection = [ { 'a': 1, 'b': '2', 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 } ]
*
* pluck(collection, ['a', 'c'])
* // => [ { 'a': 1, 'c': 3 }, { 'a': 4, 'c': 6 } ]
*/
function pluck(collection, ...paths) {
return map(collection, (item) => pick(item, paths));
}

export default pluck;
58 changes: 58 additions & 0 deletions test/pluck.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import lodashStable from 'lodash';
import { toArgs } from './utils';
import pluck from '../src/pluck';

describe('pluck', () => {
const args = toArgs(['a', 'c']);
const collection = [
{ a: 1, b: '2', c: 3 },
{ a: 4, b: 5, c: 6 },
];

it('should flatten `paths`', () => {
expect(pluck(collection, 'a', 'c')).toEqual([
{ a: 1, c: 3 },
{ a: 4, c: 6 },
]);
expect(pluck(collection, ['a', 'd'], 'c')).toEqual([
{ a: 1, c: 3 },
{ a: 4, c: 6 },
]);
});

it('should support deep paths', () => {
const nested = [{ a: 1, b: { c: 2, d: 3 } }];

expect(pluck(nested, 'b.c')).toEqual([{ b: { c: 2 } }]);
});

it('should support path arrays', () => {
const collection = [{ 'a.b': 1, a: { b: 2 } }];
const actual = pluck(collection, [['a.b']]);

expect(actual).toEqual([{ 'a.b': 1 }]);
});

it('should pluck a key over a path', () => {
const collection = [{ 'a.b': 1, a: { b: 2 } }];

lodashStable.each(['a.b', ['a.b']], (path) => {
expect(pluck(collection, path)).toEqual([{ 'a.b': 1 }]);
});
});

it('should coerce `paths` to strings', () => {
expect(pluck([{ 0: 'a', 1: 'b' }], 0)).toEqual([{ 0: 'a' }]);
});

it('should return an empty collection when `collection` is nullish', () => {
expect(pluck([[null], [undefined]], 'valueOf')).toEqual([{}, {}]);
});

it('should work with `arguments` collection `paths`', () => {
expect(pluck(collection, args)).toEqual([
{ a: 1, c: 3 },
{ a: 4, c: 6 },
]);
});
});

0 comments on commit 71900aa

Please sign in to comment.