Initial implementation of _.chunk - close #465

This commit is contained in:
Blaine Bublitz
2014-06-11 16:58:26 -07:00
parent 3c5655fc3d
commit a58ad5006f
2 changed files with 54 additions and 1 deletions

View File

@@ -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;

View File

@@ -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._;