Ensure _.sum provides the correct arguments when iterating an object.

This commit is contained in:
jdalton
2015-03-15 19:29:58 -07:00
parent c58c0df30e
commit 4c1819c7dd
2 changed files with 38 additions and 11 deletions

View File

@@ -1699,6 +1699,16 @@
return false; return false;
} }
function arraySum(array) {
var length = array.length,
result = 0;
while (length--) {
result += +array[length] || 0;
}
return result;
}
/** /**
* Used by `_.defaults` to customize its `_.assign` use. * Used by `_.defaults` to customize its `_.assign` use.
* *
@@ -2747,6 +2757,14 @@
}); });
} }
function baseSum(collection, iteratee) {
var result = 0;
baseEach(collection, function(value, index, collection) {
result += +iteratee(value, index, collection) || 0;
});
return result;
}
/** /**
* The base implementation of `_.uniq` without support for callback shorthands * The base implementation of `_.uniq` without support for callback shorthands
* and `this` binding. * and `this` binding.
@@ -11333,9 +11351,6 @@
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = null; iteratee = null;
} }
if (!isArray(collection)) {
collection = toIterable(collection);
}
var func = getCallback(), var func = getCallback(),
noIteratee = iteratee == null; noIteratee = iteratee == null;
@@ -11343,14 +11358,9 @@
noIteratee = false; noIteratee = false;
iteratee = func(iteratee, thisArg, 3); iteratee = func(iteratee, thisArg, 3);
} }
var length = collection.length, return noIteratee
result = 0; ? arraySum(isArray(collection) ? collection : toIterable(collection))
: baseSum(collection, iteratee);
while (length--) {
var value = collection[length];
result += +(noIteratee ? value : iteratee(value)) || 0;
}
return result;
} }
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/

View File

@@ -13515,6 +13515,23 @@
deepEqual(actual, 6); deepEqual(actual, 6);
}); });
test('should provide the correct `iteratee` arguments', 2, function() {
var args;
_.sum(array, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [6, 0, array]);
args = null;
_.sum(object, function() {
args || (args = slice.call(arguments));
});
deepEqual(args, [2, 'a', object]);
});
test('should support the `thisArg` argument', 1, function() { test('should support the `thisArg` argument', 1, function() {
var actual = _.sum([6.8, 4.5, 2.6], function(num) { var actual = _.sum([6.8, 4.5, 2.6], function(num) {
return this.floor(num); return this.floor(num);