From c21e7b24c66af270853d8ffefa9a424d99e21a75 Mon Sep 17 00:00:00 2001 From: Elliot Winkler Date: Sun, 31 Oct 2010 18:51:30 -0600 Subject: [PATCH] Fix reduce() so that if you don't pass in an initial value, the first item in the collection is used --- test/collections.js | 3 +++ underscore.js | 10 ++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/test/collections.js b/test/collections.js index 4e7c7ab6b..87d5ccfba 100644 --- a/test/collections.js +++ b/test/collections.js @@ -65,6 +65,9 @@ $(document).ready(function() { sum = _([1, 2, 3]).reduce(function(sum, num){ return sum + num; }, 0); equals(sum, 6, 'OO-style reduce'); + + var sum = _.reduce([1, 2, 3], function(sum, num){ return sum + num; }); + equals(sum, 6, 'default initial value'); }); test('collections: reduceRight', function() { diff --git a/underscore.js b/underscore.js index 6bd1ee3ca..5f57bc951 100644 --- a/underscore.js +++ b/underscore.js @@ -94,10 +94,16 @@ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); - return obj.reduce(iterator, memo); + var args = [iterator]; + if (memo !== undefined) args.push(memo); + return obj.reduce.apply(obj, args); } each(obj, function(value, index, list) { - memo = iterator.call(context, memo, value, index, list); + if (memo === undefined && index == 0) { + memo = value; + } else { + memo = iterator.call(context, memo, value, index, list); + } }); return memo; };