diff --git a/pkg/util/math/median.go b/pkg/util/math/median.go index 116d23fa27..25dabd1784 100644 --- a/pkg/util/math/median.go +++ b/pkg/util/math/median.go @@ -3,7 +3,7 @@ package math import ( - "sort" + "slices" ) // MedianFilter provides the median value over a rolling window. @@ -23,6 +23,7 @@ func NewMedianFilter(size int) *MedianFilter { } } +// Add adds a value to the filter, sorts the values, and returns the current median. func (f *MedianFilter) Add(value float64) float64 { f.values[f.index] = value f.index = (f.index + 1) % len(f.values) @@ -33,12 +34,11 @@ func (f *MedianFilter) Add(value float64) float64 { } copy(f.sorted, f.values) - sort.Slice(f.sorted, func(i, j int) bool { - return f.sorted[i] < f.sorted[j] - }) + slices.Sort(f.sorted) return f.Median() } +// Median returns the current median, else 0 if the filter isn't full yet. func (f *MedianFilter) Median() float64 { if f.size < len(f.values)-1 { return 0 diff --git a/pkg/util/math/median_test.go b/pkg/util/math/median_test.go index aa9322f87f..3a42114d22 100644 --- a/pkg/util/math/median_test.go +++ b/pkg/util/math/median_test.go @@ -9,10 +9,10 @@ import ( ) func TestMedianFilter(t *testing.T) { - t.Run("single value", func(t *testing.T) { + t.Run("not full window", func(t *testing.T) { filter := NewMedianFilter(3) - result := filter.Add(5.0) - assert.Equal(t, 5.0, result) + median := filter.Add(5.0) + assert.Equal(t, 5.0, median) assert.Equal(t, 0.0, filter.Median()) }) @@ -29,8 +29,8 @@ func TestMedianFilter(t *testing.T) { filter.Add(1.0) filter.Add(2.0) filter.Add(3.0) - result := filter.Add(4.0) - assert.Equal(t, 3.0, result) + median := filter.Add(4.0) + assert.Equal(t, 3.0, median) }) t.Run("unsorted input", func(t *testing.T) { @@ -39,7 +39,7 @@ func TestMedianFilter(t *testing.T) { filter.Add(2.0) filter.Add(8.0) filter.Add(1.0) - result := filter.Add(9.0) - assert.Equal(t, 5.0, result) + median := filter.Add(9.0) + assert.Equal(t, 5.0, median) }) }