-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathpoint.go
47 lines (40 loc) · 1.12 KB
/
point.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
package rolling
import "sync"
// PointPolicy is a rolling window policy that tracks the last N
// values inserted regardless of insertion time.
type PointPolicy struct {
windowSize int
window Window
offset int
lock *sync.RWMutex
}
// NewPointPolicy generates a Policy that operates on a rolling set of
// input points. The number of points is determined by the size of the given
// window. Each bucket will contain, at most, one data point when the window
// is full.
func NewPointPolicy(window Window) *PointPolicy {
var p = &PointPolicy{
windowSize: len(window),
window: window,
lock: &sync.RWMutex{},
}
for offset, bucket := range window {
if len(bucket) < 1 {
window[offset] = make([]float64, 1)
}
}
return p
}
// Append a value to the window.
func (w *PointPolicy) Append(value float64) {
w.lock.Lock()
defer w.lock.Unlock()
w.window[w.offset][0] = value
w.offset = (w.offset + 1) % w.windowSize
}
// Reduce the window to a single value using a reduction function.
func (w *PointPolicy) Reduce(f func(Window) float64) float64 {
w.lock.Lock()
defer w.lock.Unlock()
return f(w.window)
}