-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (43 loc) · 1.09 KB
/
index.js
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
// expose `sum`
module.exports = sum;
var selectn = require('selectn');
var toString = ({}).toString;
/**
* Returns the sum of a list supporting number literals, nested objects, or transformation function.
*
* #### Number literals
*
* sum([1, 2, 3, 4])
* //=> 10
*
* #### Nested object properties
*
* var strings = [ 'literal', 'constructor' ];
* sum(strings, 'length');
* //=> 18
*
* #### Custom function
*
* sum([1, 2, 3, 4], function (n) { n * 60 });
* //=> 600
*
* @param {Array} list
* list of numbers or list that will contain numbers after transforming.
*
* @param {Function|String} [fun]
* function which is given the current item and returns a number to be included in sum
* or dot notation object property string (i.e. `length`).
*
* @return {Array}
* sum of list
*/
function sum(list, fun) {
fun = toString.call(fun) == '[object String]' ? selectn(fun) : fun;
end = list.length;
sum = -0;
idx = -1;
while (++idx < end) {
sum += typeof fun == 'function' ? fun(list[idx]) * 1000 : list[idx] * 1000;
}
return sum && (sum / 1000);
}