From 41555ffad487dca57574fd1ecb867156f898386c Mon Sep 17 00:00:00 2001 From: Justin Ridgewell Date: Thu, 4 Dec 2014 14:22:52 -0500 Subject: [PATCH] Remove `reduce` error throwing Closes #1858. --- test/collections.js | 8 ++------ underscore.js | 6 +----- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/test/collections.js b/test/collections.js index dd0c67bb0..4ee48a3bd 100644 --- a/test/collections.js +++ b/test/collections.js @@ -122,9 +122,7 @@ ok(_.reduce(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); equal(_.reduce([], _.noop, undefined), undefined, 'undefined can be passed as a special case'); equal(_.reduce([_], _.noop), _, 'collection of length one with no initial value returns the first item'); - - throws(function() { _.reduce([], _.noop); }, TypeError, 'throws an error for empty arrays with no initial value'); - throws(function() {_.reduce(null, _.noop);}, TypeError, 'handles a null (without initial value) properly'); + equal(_.reduce([], _.noop), undefined, 'returns undefined when collection is empty and no initial value'); }); test('foldl', function() { @@ -145,9 +143,7 @@ equal(_.reduceRight([_], _.noop), _, 'collection of length one with no initial value returns the first item'); equal(_.reduceRight([], _.noop, undefined), undefined, 'undefined can be passed as a special case'); - - throws(function() { _.reduceRight([], _.noop); }, TypeError, 'throws an error for empty arrays with no initial value'); - throws(function() {_.reduceRight(null, _.noop);}, TypeError, 'handles a null (without initial value) properly'); + equal(_.reduceRight([], _.noop), undefined, 'returns undefined when collection is empty and no initial value'); // Assert that the correct arguments are being passed. diff --git a/underscore.js b/underscore.js index 246b98136..a425530f0 100644 --- a/underscore.js +++ b/underscore.js @@ -160,8 +160,6 @@ return results; }; - var reduceError = 'Reduce of empty array with no initial value'; - // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { @@ -171,7 +169,6 @@ length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { - if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { @@ -189,10 +186,9 @@ index = (keys || obj).length, currentKey; if (arguments.length < 3) { - if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } - while (index--) { + while (index-- > 0) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); }