From f599c4817aa9e799be9ef681092511c4186ced4a Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Fri, 1 Apr 2016 17:21:16 -0700 Subject: [PATCH] Make `_.chunk` default `size` to `1` instead of `0`. --- lodash.js | 12 ++++++++---- test/test.js | 27 ++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/lodash.js b/lodash.js index 2dc0bf6ae..bada755de 100644 --- a/lodash.js +++ b/lodash.js @@ -5769,7 +5769,8 @@ * @since 3.0.0 * @category Array * @param {Array} array The array to process. - * @param {number} [size=0] The length of each chunk. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array containing chunks. * @example * @@ -5779,9 +5780,12 @@ * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ - function chunk(array, size) { - size = nativeMax(toInteger(size), 0); - + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } var length = array ? array.length : 0; if (!length || size < 1) { return []; diff --git a/test/test.js b/test/test.js index fc893a171..6b7866f87 100644 --- a/test/test.js +++ b/test/test.js @@ -2385,14 +2385,28 @@ assert.deepEqual(actual, [[0, 1, 2, 3], [4, 5]]); }); + QUnit.test('should treat falsey `size` values, except `undefined`, as `0`', function(assert) { + assert.expect(1); + + var expected = lodashStable.map(falsey, function(value) { + return value === undefined ? [[0], [1], [2], [3], [4], [5]] : []; + }); + + var actual = lodashStable.map(falsey, function(size, index) { + return index ? _.chunk(array, size) : _.chunk(array); + }); + + assert.deepEqual(actual, expected); + }); + QUnit.test('should ensure the minimum `size` is `0`', function(assert) { assert.expect(1); - var values = falsey.concat(-1, -Infinity), + var values = lodashStable.reject(falsey, lodashStable.isUndefined).concat(-1, -Infinity), expected = lodashStable.map(values, alwaysEmptyArray); - var actual = lodashStable.map(values, function(value, index) { - return index ? _.chunk(array, value) : _.chunk(array); + var actual = lodashStable.map(values, function(n) { + return _.chunk(array, n); }); assert.deepEqual(actual, expected); @@ -2403,6 +2417,13 @@ assert.deepEqual(_.chunk(array, array.length / 4), [[0], [1], [2], [3], [4], [5]]); }); + + QUnit.test('should work as an iteratee for methods like `_.map`', function(assert) { + assert.expect(1); + + var actual = lodashStable.map([[1, 2], [3, 4]], _.chunk); + assert.deepEqual(actual, [[[1], [2]], [[3], [4]]]); + }); }()); /*--------------------------------------------------------------------------*/