/
maverage.go
68 lines (49 loc) · 1.08 KB
/
maverage.go
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
package aggregator
import "sync"
type MovingAverage struct {
windowSize int
values []float64
nextValueIdx int
full bool
mutex *sync.Mutex
}
func init() {
RegisterFactory("moving_avg", NewMovingAverage)
}
func (ma *MovingAverage) Add(value float64) (bool, float64) {
ma.mutex.Lock()
defer ma.mutex.Unlock()
//if ma.full && ma.nextValueIdx == 0 && ma.autoReset {
// ma.full = false
//}
ma.values[ma.nextValueIdx] = value
ma.nextValueIdx = (ma.nextValueIdx + 1) % ma.windowSize
if !ma.full && ma.nextValueIdx == 0 {
ma.full = true
}
if ma.full {
return true, ma.result()
}
return false, 0
}
func (ma *MovingAverage) result() float64 {
var total = float64(0)
var count = ma.windowSize
if !ma.full {
if ma.nextValueIdx == 0 {
return 0
}
count = ma.nextValueIdx
}
for i := 0; i < count; i++ {
total += ma.values[i]
}
return total / float64(count)
}
func NewMovingAverage(windowSize int) Aggregator {
return &MovingAverage{
windowSize: windowSize,
values: make([]float64, windowSize),
mutex: &sync.Mutex{},
}
}