1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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');
/**
* Gets the sum of the values in `collection`.
*
* @static
* @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]);
* // => 10
*
* _.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, iteratee, thisArg) {
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
iteratee = undefined;
}
iteratee = baseCallback(iteratee, thisArg, 3);
return iteratee.length == 1
? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
: baseSum(collection, iteratee);
}
module.exports = sum;
|