-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
84 lines (73 loc) · 2.23 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
/**
* Calculate the simple moving average of an array. A new array is returned with the average
* of each range of elements. A range will only be calculated when it contains enough elements to fill the range.
*
* ```js
* console.log(sma([1, 2, 3, 4, 5, 6, 7, 8, 9], 4));
* //=> [ '2.50', '3.50', '4.50', '5.50', '6.50', '7.50' ]
* //=> │ │ │ │ │ └─(6+7+8+9)/4
* //=> │ │ │ │ └─(5+6+7+8)/4
* //=> │ │ │ └─(4+5+6+7)/4
* //=> │ │ └─(3+4+5+6)/4
* //=> │ └─(2+3+4+5)/4
* //=> └─(1+2+3+4)/4
* ```
* @param {Array} `arr` Array of numbers to calculate.
* @param {Number} `range` Size of the window to use to when calculating the average for each range. Defaults to array length.
* @param {Function} `format` Custom format function called on each calculated average. Defaults to `n.toFixed(2)`.
* @return {Array} Resulting array of averages.
* @api public
*/
function sma(arr, range, format) {
if (!Array.isArray(arr)) {
throw TypeError('expected first argument to be an array');
}
var fn = typeof format === 'function' ? format : toFixed;
var num = range || arr.length;
var res = [];
var len = arr.length + 1;
var idx = num - 1;
while (++idx < len) {
res.push(fn(avg(arr, idx, num)));
}
return res;
}
/**
* Create an average for the specified range.
*
* ```js
* console.log(avg([1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 4));
* //=> 3.5
* ```
* @param {Array} `arr` Array to pull the range from.
* @param {Number} `idx` Index of element being calculated
* @param {Number} `range` Size of range to calculate.
* @return {Number} Average of range.
*/
function avg(arr, idx, range) {
return sum(arr.slice(idx - range, idx)) / range;
}
/**
* Calculate the sum of an array.
* @param {Array} `arr` Array
* @return {Number} Sum
*/
function sum(arr) {
var len = arr.length;
var num = 0;
while (len--) num += Number(arr[len]);
return num;
}
/**
* Default format method.
* @param {Number} `n` Number to format.
* @return {String} Formatted number.
*/
function toFixed(n) {
return n.toFixed(2);
}
/**
* Expose `sma`
*/
module.exports = sma;