From 8f2cf3ce5a456cba07fc3e883d5dad8c30b09647 Mon Sep 17 00:00:00 2001 From: sqshq Date: Mon, 15 Apr 2019 23:00:41 -0400 Subject: [PATCH] sparkline values cleanup enhancements and test --- component/sparkline/sparkline.go | 9 ++++++-- component/sparkline/sparkline_test.go | 31 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 component/sparkline/sparkline_test.go diff --git a/component/sparkline/sparkline.go b/component/sparkline/sparkline.go index 2e4aa84..09735a3 100644 --- a/component/sparkline/sparkline.go +++ b/component/sparkline/sparkline.go @@ -77,9 +77,14 @@ func (s *SparkLine) consumeSample(sample *data.Sample) { s.maxValue = max s.minValue = min - // perform cleanup once in a while if len(s.values)%100 == 0 { - s.values = append(s.values[:0], s.values[len(s.values)-s.Dx()+1:]...) + s.cleanup(s.Dx()) + } +} + +func (s *SparkLine) cleanup(maxSize int) { + if maxSize < len(s.values) { + s.values = append(s.values[:0], s.values[len(s.values)-maxSize:]...) } } diff --git a/component/sparkline/sparkline_test.go b/component/sparkline/sparkline_test.go new file mode 100644 index 0000000..575f243 --- /dev/null +++ b/component/sparkline/sparkline_test.go @@ -0,0 +1,31 @@ +package sparkline + +import ( + "testing" +) + +func TestSparkLine_cleanup(t *testing.T) { + type Sparkline struct { + maxSize int + expectedSize int + values []float64 + } + tests := []struct { + name string + sparkline Sparkline + }{ + {"should cleanup values to the max size", Sparkline{maxSize: 5, expectedSize: 5, values: []float64{1, 2, 3, 4, 5, 6, 7, 8}}}, + {"should not cleanup values if max size is bigger than values len", Sparkline{maxSize: 5, expectedSize: 3, values: []float64{1, 2, 3}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := &SparkLine{ + values: tt.sparkline.values, + } + s.cleanup(tt.sparkline.maxSize) + if len(s.values) != tt.sparkline.expectedSize { + t.Errorf("Values size after cleanup is %v, but needed to be %v", len(s.values), tt.sparkline.expectedSize) + } + }) + } +}