diff --git a/pkg/services/alerting/conditions/reducer.go b/pkg/services/alerting/conditions/reducer.go index 988a640591d..b2d17f4f8ab 100644 --- a/pkg/services/alerting/conditions/reducer.go +++ b/pkg/services/alerting/conditions/reducer.go @@ -3,6 +3,8 @@ package conditions import ( "math" + "sort" + "github.com/grafana/grafana/pkg/tsdb" "gopkg.in/guregu/null.v3" ) @@ -71,6 +73,24 @@ func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) null.Float { break } } + case "median": + var values []float64 + for _, v := range series.Points { + if v[0].Valid { + allNull = false + values = append(values, v[0].Float64) + } + } + if len(values) >= 1 { + sort.Float64s(values) + length := len(values) + if length%2 == 1 { + value = values[(length-1)/2] + } else { + value = (values[(length/2)-1] + values[length/2]) / 2 + } + } + } if allNull { diff --git a/pkg/services/alerting/conditions/reducer_test.go b/pkg/services/alerting/conditions/reducer_test.go index dfd229e1374..477595c5af1 100644 --- a/pkg/services/alerting/conditions/reducer_test.go +++ b/pkg/services/alerting/conditions/reducer_test.go @@ -41,6 +41,20 @@ func TestSimpleReducer(t *testing.T) { So(result, ShouldEqual, float64(3000)) }) + Convey("median odd amount of numbers", func() { + result := testReducer("median", 1, 2, 3000) + So(result, ShouldEqual, float64(2)) + }) + + Convey("median even amount of numbers", func() { + result := testReducer("median", 1, 2, 4, 3000) + So(result, ShouldEqual, float64(3)) + }) + + Convey("median with one values", func() { + result := testReducer("median", 1) + So(result, ShouldEqual, float64(1)) + }) }) }