From a58ad5006fea418a0ae25ec35f89071b78c2aab0 Mon Sep 17 00:00:00 2001 From: Blaine Bublitz Date: Wed, 11 Jun 2014 16:58:26 -0700 Subject: [PATCH] Initial implementation of _.chunk - close #465 --- lodash.js | 30 ++++++++++++++++++++++++++++++ test/test.js | 25 ++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/lodash.js b/lodash.js index d5039ce7b..01c7811e2 100644 --- a/lodash.js +++ b/lodash.js @@ -3998,6 +3998,35 @@ return baseAt(collection, baseFlatten(arguments, true, false, 1)); } + /** + * Creates an array of elements split into groups the length of `chunkSize`. + * If `collection` cannot be split evenly, the final chunk will be the remaining elements. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {numer} chunkSize The size of each chunk. + * @returns {Array} Returns the new array containing chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(collection, chunkSize) { + var index = 0, + length = collection ? collection.length : 0, + result = []; + + while (index < length) { + result.push(slice(collection, index, (index += chunkSize))); + } + return result; + } + /** * Checks if `value` is present in `collection` using strict equality for * comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the @@ -8611,6 +8640,7 @@ lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.chain = chain; + lodash.chunk = chunk; lodash.compact = compact; lodash.compose = compose; lodash.constant = constant; diff --git a/test/test.js b/test/test.js index 059ecfd1d..e1803d2a9 100644 --- a/test/test.js +++ b/test/test.js @@ -1211,6 +1211,29 @@ /*--------------------------------------------------------------------------*/ + QUnit.module('lodash.chunk'); + + (function() { + var array = [0, 1, 2, 3, 4, 5]; + + test('should return chunked arrays', 1, function() { + var actual = _.chunk(array, 3); + deepEqual(actual, [[0, 1, 2], [3, 4, 5]]); + }); + + test('should return the last chunk as remaining elements', 1, function() { + var actual = _.chunk(array, 4); + deepEqual(actual, [[0, 1, 2, 3], [4, 5]]); + }); + + test('should ignore falsey values', 1, function() { + var actual = _.chunk(false, 3); + deepEqual(actual, []); + }); + }()); + + /*--------------------------------------------------------------------------*/ + QUnit.module('cloning'); (function() { @@ -10918,7 +10941,7 @@ var acceptFalsey = _.difference(allMethods, rejectFalsey); - test('should accept falsey arguments', 187, function() { + test('should accept falsey arguments', 188, function() { var emptyArrays = _.map(falsey, _.constant([])), isExposed = '_' in root, oldDash = root._;