-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
68 lines (54 loc) · 1.28 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
'use strict'
const exp = Math.exp
exports =
module.exports =
function MovingAverage (timespan) {
if (typeof timespan !== 'number') { throw new Error('must provide a timespan to the moving average constructor') }
if (timespan <= 0) { throw new Error('must provide a timespan > 0 to the moving average constructor') }
let ma // moving average
let v = 0 // variance
let d = 0 // deviation
let f = 0 // forecast
let previousTime
let ret = {}
function alpha (t, pt) {
return 1 - (exp(-(t - pt) / timespan))
}
ret.push =
function push (time, value) {
if (previousTime) {
// calculate moving average
const a = alpha(time, previousTime)
const diff = value - ma
const incr = a * diff
ma = a * value + (1 - a) * ma
// calculate variance & deviation
v = (1 - a) * (v + diff * incr)
d = Math.sqrt(v)
// calculate forecast
f = ma + a * diff
} else {
ma = value
}
previousTime = time
}
// Exponential Moving Average
ret.movingAverage =
function movingAverage () {
return ma
}
// Variance
ret.variance =
function variance () {
return v
}
ret.deviation =
function deviation () {
return d
}
ret.forecast =
function forecast () {
return f
}
return ret
}