This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
func_sortby.go
87 lines (72 loc) · 2.05 KB
/
func_sortby.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package expr
import (
"math"
"sort"
"github.com/grafana/metrictank/consolidation"
"github.com/grafana/metrictank/api/models"
)
type FuncSortBy struct {
in GraphiteFunc
fn string
reverse bool
}
func NewSortByConstructor(fn string, reverse bool) func() GraphiteFunc {
return func() GraphiteFunc {
return &FuncSortBy{fn: fn, reverse: reverse}
}
}
func (s *FuncSortBy) Signature() ([]Arg, []Arg) {
if s.fn != "" {
return []Arg{
ArgSeriesList{val: &s.in},
}, []Arg{ArgSeriesList{}}
}
return []Arg{
ArgSeriesList{val: &s.in},
ArgString{key: "func", val: &s.fn, validator: []Validator{IsConsolFunc}},
ArgBool{key: "reverse", val: &s.reverse, opt: true},
}, []Arg{ArgSeriesList{}}
}
func (s *FuncSortBy) Context(context Context) Context {
return context
}
func (s *FuncSortBy) Exec(dataMap DataMap) ([]models.Series, error) {
series, err := s.in.Exec(dataMap)
if err != nil {
return nil, err
}
// Copy series to avoid conflicting with other functions
seriesCpy := make([]models.Series, 0, len(series))
for _, serie := range series {
seriesCpy = append(seriesCpy, serie)
}
// note that s.fn has already been validated at series construction time using consolidation.IsConsolFunc
SortSeriesWithConsolidator(seriesCpy, consolidation.FromConsolidateBy(s.fn), s.reverse)
return seriesCpy, nil
}
type ScoredSeries struct {
score float64
serie models.Series
}
func SortSeriesWithConsolidator(series []models.Series, c consolidation.Consolidator, reverse bool) {
consolidationFunc := consolidation.GetAggFunc(c)
// score series by their consolidated value
scored := make([]ScoredSeries, len(series))
for i, serie := range series {
scored[i] = ScoredSeries{
score: consolidationFunc(serie.Datapoints),
serie: serie,
}
}
sort.SliceStable(scored, func(i, j int) bool {
iVal := scored[i].score
jVal := scored[j].score
if reverse {
return math.IsNaN(jVal) && !math.IsNaN(iVal) || iVal > jVal
}
return math.IsNaN(iVal) && !math.IsNaN(jVal) || iVal < jVal
})
for i := range scored {
series[i] = scored[i].serie
}
}