Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var arraySum = require('../internal/arraySum'),
2
baseCallback = require('../internal/baseCallback'),
3
baseSum = require('../internal/baseSum'),
4
isArray = require('../lang/isArray'),
5
isIterateeCall = require('../internal/isIterateeCall'),
6
toIterable = require('../internal/toIterable');
7
8
/**
9
* Gets the sum of the values in `collection`.
10
*
11
* @static
12
* @memberOf _
13
* @category Math
14
* @param {Array|Object|string} collection The collection to iterate over.
15
* @param {Function|Object|string} [iteratee] The function invoked per iteration.
16
* @param {*} [thisArg] The `this` binding of `iteratee`.
17
* @returns {number} Returns the sum.
18
* @example
19
*
20
* _.sum([4, 6]);
21
* // => 10
22
*
23
* _.sum({ 'a': 4, 'b': 6 });
24
* // => 10
25
*
26
* var objects = [
27
* { 'n': 4 },
28
* { 'n': 6 }
29
* ];
30
*
31
* _.sum(objects, function(object) {
32
* return object.n;
33
* });
34
* // => 10
35
*
36
* // using the `_.property` callback shorthand
37
* _.sum(objects, 'n');
38
* // => 10
39
*/
40
function sum(collection, iteratee, thisArg) {
41
if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
42
iteratee = null;
43
}
44
var noIteratee = iteratee == null;
45
46
iteratee = noIteratee ? iteratee : baseCallback(iteratee, thisArg, 3);
47
return noIteratee
48
? arraySum(isArray(collection) ? collection : toIterable(collection))
49
: baseSum(collection, iteratee);
50
}
51
52
module.exports = sum;
53
54