Fix reduce() so that if you don't pass in an initial value, the first item in the collection is used

This commit is contained in:
Elliot Winkler
2010-10-31 18:51:30 -06:00
parent 31efd854f8
commit c21e7b24c6
2 changed files with 11 additions and 2 deletions

View File

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