reducer.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package conditions
  2. import (
  3. "math"
  4. "github.com/grafana/grafana/pkg/tsdb"
  5. )
  6. type QueryReducer interface {
  7. Reduce(timeSeries *tsdb.TimeSeries) *float64
  8. }
  9. type SimpleReducer struct {
  10. Type string
  11. }
  12. func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) *float64 {
  13. if len(series.Points) == 0 {
  14. return nil
  15. }
  16. value := float64(0)
  17. allNull := true
  18. switch s.Type {
  19. case "avg":
  20. for _, point := range series.Points {
  21. if point[0] != nil {
  22. value += *point[0]
  23. allNull = false
  24. }
  25. }
  26. value = value / float64(len(series.Points))
  27. case "sum":
  28. for _, point := range series.Points {
  29. if point[0] != nil {
  30. value += *point[0]
  31. allNull = false
  32. }
  33. }
  34. case "min":
  35. value = math.MaxFloat64
  36. for _, point := range series.Points {
  37. if point[0] != nil {
  38. allNull = false
  39. if value > *point[0] {
  40. value = *point[0]
  41. }
  42. }
  43. }
  44. case "max":
  45. value = -math.MaxFloat64
  46. for _, point := range series.Points {
  47. if point[0] != nil {
  48. allNull = false
  49. if value < *point[0] {
  50. value = *point[0]
  51. }
  52. }
  53. }
  54. case "count":
  55. value = float64(len(series.Points))
  56. allNull = false
  57. }
  58. if allNull {
  59. return nil
  60. }
  61. return &value
  62. }
  63. func NewSimpleReducer(typ string) *SimpleReducer {
  64. return &SimpleReducer{Type: typ}
  65. }