mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-05 01:17:50 +00:00
Bump to v3.6.0.
This commit is contained in:
47
math/sum.js
47
math/sum.js
@@ -1,4 +1,8 @@
|
||||
var isArray = require('../lang/isArray'),
|
||||
var arraySum = require('../internal/arraySum'),
|
||||
baseCallback = require('../internal/baseCallback'),
|
||||
baseSum = require('../internal/baseSum'),
|
||||
isArray = require('../lang/isArray'),
|
||||
isIterateeCall = require('../internal/isIterateeCall'),
|
||||
toIterable = require('../internal/toIterable');
|
||||
|
||||
/**
|
||||
@@ -8,26 +12,41 @@ var isArray = require('../lang/isArray'),
|
||||
* @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);
|
||||
}
|
||||
|
||||
module.exports = sum;
|
||||
|
||||
Reference in New Issue
Block a user