From 11ba02067e734d33a2767e4618ce6fdb526aabd0 Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Thu, 7 Mar 2013 09:05:27 -0800 Subject: [PATCH] Ensure `_.times` doesn't error when passed negative numbers. Former-commit-id: 5d694743fbda0f477250fe3c90cf29168834ac6f --- build.js | 13 +++++++++++++ lodash.js | 2 +- test/test-build.js | 1 + test/test.js | 14 ++++++++++++++ 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/build.js b/build.js index cb9b3e4c7..61c21ee2b 100755 --- a/build.js +++ b/build.js @@ -2170,6 +2170,19 @@ '}' ].join('\n')); + // replace `_.times` + source = replaceFunction(source, 'times', [ + 'function times(n, callback, thisArg) {', + ' var index = -1,', + ' result = Array(n > -1 ? n : 0);', + '', + ' while (++index < n) {', + ' result[index] = callback.call(thisArg, index);', + ' }', + ' return result;', + '}' + ].join('\n')); + // replace `_.uniq` source = replaceFunction(source, 'uniq', [ 'function uniq(array, isSorted, callback, thisArg) {', diff --git a/lodash.js b/lodash.js index 0b0e7f87d..c512e7cdb 100644 --- a/lodash.js +++ b/lodash.js @@ -4973,7 +4973,7 @@ * // => also calls `mage.castSpell(n)` three times */ function times(n, callback, thisArg) { - n = +n || 0; + n = (n = +n) > -1 ? n : 0; var index = -1, result = Array(n); diff --git a/test/test-build.js b/test/test-build.js index dec90fa56..9aa509c3a 100644 --- a/test/test-build.js +++ b/test/test-build.js @@ -911,6 +911,7 @@ strictEqual(lodash.result(), null, '_.result should return `null` for falsey `object` arguments: ' + basename); strictEqual(lodash.some([false, true, false]), true, '_.some: ' + basename); + deepEqual(lodash.times(null, function() {}), [null], '_.times should not coerce `n` to a number: ' + basename); equal(lodash.template('${a}', object), '${a}', '_.template should ignore ES6 delimiters: ' + basename); equal('imports' in lodash.templateSettings, false, '_.templateSettings should not have an "imports" property: ' + basename); strictEqual(lodash.uniqueId(0), '1', '_.uniqueId should ignore a prefix of `0`: ' + basename); diff --git a/test/test.js b/test/test.js index 85d9837ac..a4b4a810d 100644 --- a/test/test.js +++ b/test/test.js @@ -2603,6 +2603,20 @@ test('should return an array of the results of each `callback` execution', function() { deepEqual(_.times(3, function(n) { return n * 2; }), [0, 2, 4]); }); + + test('should coerce `n` to a number', function() { + deepEqual(_.times(null), []); + }); + + test('should not error on negative `n` values', function() { + var pass = true; + try { + _.times(-1); + } catch(e) { + pass = false; + } + ok(pass); + }); }()); /*--------------------------------------------------------------------------*/