-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.go
69 lines (60 loc) · 1.53 KB
/
history.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
69
package main
import (
"math"
"time"
)
type Sample struct {
timestamp float64
value float64
}
type History struct {
Samples []Sample
}
const MaxHistorySamples = 512
func NewHistory() History {
return History{Samples: make([]Sample, 0)}
}
// Add a new sample at the end of history and maintain max history size
func (h *History) Add(sample Sample) {
if !time.Unix(int64(sample.timestamp), 0).IsZero() {
h.Samples = append(h.Samples, sample)
if len(h.Samples) > MaxHistorySamples {
copy(h.Samples[0:], h.Samples[len(h.Samples)-MaxHistorySamples:])
h.Samples = h.Samples[:MaxHistorySamples]
}
}
}
// GetXY return history samples as two arrays for x and y data
func (h *History) GetXY() ([]float64, []float64) {
x := make([]float64, len(h.Samples))
y := make([]float64, len(h.Samples))
for idx, sample := range h.Samples {
x[idx] = sample.timestamp
y[idx] = sample.value
}
return x, y
}
// GetYMinMax returns the minimum and maximum value found in history
func (h *History) GetYMinMax(from, until float64) (float64, float64) {
min := math.MaxFloat64
max := -math.MaxFloat64
for _, sample := range h.Samples {
if sample.timestamp >= from && sample.timestamp <= until {
max = math.Max(max, sample.value)
min = math.Min(min, sample.value)
}
}
return min, max
}
func (h *History) GetYAvg(from, until float64) float64 {
avg := 0.
samples := 0
for _, sample := range h.Samples {
if sample.timestamp >= from && sample.timestamp <= until {
avg += sample.value
samples++
}
}
avg /= float64(samples)
return avg
}