From 2ae0e9d902fd6ba357696267d069e54f750aa817 Mon Sep 17 00:00:00 2001 From: Dan Heberden Date: Tue, 18 Dec 2012 10:00:24 -0800 Subject: [PATCH] add `grab` method to get elements in a collection that match the indexes in the provided list array Former-commit-id: 18df81c229cab4acde8f8157df9bb1001a51e9db --- lodash.js | 20 ++++++++++++++++++++ test/test.js | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lodash.js b/lodash.js index 7e659648c..f3d8b4634 100644 --- a/lodash.js +++ b/lodash.js @@ -2175,6 +2175,25 @@ return collection; } + /** + * Grabs the elements in the `collection` using the specified indexes + * in the `list` array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Array} list The array of indexes to grab. + * @ returns {Array} Returns a new array of elements that matched the list array. + * @example + * + * _.grab( ['a', 'b', 'c', 'd', 'e', 'f'], [0, 2, 5] ); + * // => ['a', 'c', 'f'] + */ + function grab(collection, list) { + return invoke(list, function(a){ return a[this]; }, collection); + } + /** * Creates an object composed of keys returned from running each element of * `collection` through a `callback`. The corresponding value of each key is an @@ -4239,6 +4258,7 @@ lodash.forIn = forIn; lodash.forOwn = forOwn; lodash.functions = functions; + lodash.grab = grab; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; diff --git a/test/test.js b/test/test.js index c1b12c470..7b767d449 100644 --- a/test/test.js +++ b/test/test.js @@ -667,6 +667,28 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.grab'); + + (function() { + test('should get items in range', function() { + var result = _.grab(['a', 'b', 1.4, 'c', { 'foo': 'bar' }, 'd'], [0, 2, 4]); + deepEqual( result, ['a', 1.4, { 'foo': 'bar' } ]); + }); + test('should work with an object for `collection`', function() { + var result = _.grab({ 'a': 'apple', 'b': 'ball', 'c': 'count' }, ['a', 'c']); + deepEqual(result, ['apple', 'count']); + }); + test('no list should return an empty array', function() { + deepEqual(_.grab(['a', 'b', 'c']), [] ); + }); + test('out of range selections should return undefined', function() { + var result = _.grab(['a', 'b', 'c'], [1, 9001]); + deepEqual( result, ['b', undefined]); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.groupBy'); (function() {