-
Notifications
You must be signed in to change notification settings - Fork 6
/
SparkRing.go
68 lines (53 loc) · 1.16 KB
/
SparkRing.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 main
type (
// SparkRing is a ring structure to draw a spark line in a terminal.
SparkRing struct {
Ring []float64
tail int
}
)
var (
steps = []rune{' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'}
)
// NewSparkRing will instantiate a new SparkRing with a length of len.
func NewSparkRing(len int) *SparkRing {
return &SparkRing{
Ring: make([]float64, len),
}
}
// Push will push a new value to the ring.
func (s *SparkRing) Push(value float64) {
if s.tail >= len(s.Ring) {
s.tail = 0
}
s.Ring[s.tail] = value
s.tail++
}
// Max will return the maximum value stored in the ring.
func (s *SparkRing) Max() float64 {
var max float64
for _, value := range s.Ring {
if value > max {
max = value
}
}
return max
}
// String will return the sparkline as a string.
func (s *SparkRing) String() string {
ret := make([]rune, len(s.Ring))
stepSize := s.Max() / float64(len(steps))
for i, value := range s.Ring {
scaled := value / stepSize
pos := int(scaled - 0.5)
if pos > len(steps)-1 {
pos = len(steps) - 1
}
if pos < 0 {
pos = 0
}
l := len(s.Ring)
ret[(l+i-s.tail)%l] = steps[pos]
}
return string(ret)
}