mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-02 16:17:50 +00:00
Bump to v3.6.0.
This commit is contained in:
45
math/sum.js
45
math/sum.js
@@ -1,4 +1,8 @@
|
||||
import arraySum from '../internal/arraySum';
|
||||
import baseCallback from '../internal/baseCallback';
|
||||
import baseSum from '../internal/baseSum';
|
||||
import isArray from '../lang/isArray';
|
||||
import isIterateeCall from '../internal/isIterateeCall';
|
||||
import toIterable from '../internal/toIterable';
|
||||
|
||||
/**
|
||||
@@ -8,26 +12,41 @@ import toIterable from '../internal/toIterable';
|
||||
* @memberOf _
|
||||
* @category Math
|
||||
* @param {Array|Object|string} collection The collection to iterate over.
|
||||
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
|
||||
* @param {*} [thisArg] The `this` binding of `iteratee`.
|
||||
* @returns {number} Returns the sum.
|
||||
* @example
|
||||
*
|
||||
* _.sum([4, 6, 2]);
|
||||
* // => 12
|
||||
* _.sum([4, 6]);
|
||||
* // => 10
|
||||
*
|
||||
* _.sum({ 'a': 4, 'b': 6, 'c': 2 });
|
||||
* // => 12
|
||||
* _.sum({ 'a': 4, 'b': 6 });
|
||||
* // => 10
|
||||
*
|
||||
* var objects = [
|
||||
* { 'n': 4 },
|
||||
* { 'n': 6 }
|
||||
* ];
|
||||
*
|
||||
* _.sum(objects, function(object) {
|
||||
* return object.n;
|
||||
* });
|
||||
* // => 10
|
||||
*
|
||||
* // using the `_.property` callback shorthand
|
||||
* _.sum(objects, 'n');
|
||||
* // => 10
|
||||
*/
|
||||
function sum(collection) {
|
||||
if (!isArray(collection)) {
|
||||
collection = toIterable(collection);
|
||||
function sum(collection, iteratee, thisArg) {
|
||||
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
|
||||
iteratee = null;
|
||||
}
|
||||
var length = collection.length,
|
||||
result = 0;
|
||||
var noIteratee = iteratee == null;
|
||||
|
||||
while (length--) {
|
||||
result += +collection[length] || 0;
|
||||
}
|
||||
return result;
|
||||
iteratee = noIteratee ? iteratee : baseCallback(iteratee, thisArg, 3);
|
||||
return noIteratee
|
||||
? arraySum(isArray(collection) ? collection : toIterable(collection))
|
||||
: baseSum(collection, iteratee);
|
||||
}
|
||||
|
||||
export default sum;
|
||||
|
||||
Reference in New Issue
Block a user