Return results in a stable order

This commit is contained in:
Alexander Zobnin
2021-05-28 12:34:04 +03:00
parent 98b6a34fb1
commit 393932068d
3 changed files with 45 additions and 27 deletions

33
pkg/timeseries/sort.go Normal file
View File

@@ -0,0 +1,33 @@
package timeseries
import (
"sort"
)
// SortBy sorts series by value calculated with provided aggFunc in given order
func SortBy(series []*TimeSeriesData, order string, aggFunc AggFunc) []*TimeSeriesData {
aggregatedSeries := make([]TimeSeries, len(series))
for i, s := range series {
aggregatedSeries[i] = s.TS.GroupByRange(aggFunc)
}
// Sort by aggregated value
sort.Slice(series, func(i, j int) bool {
if len(aggregatedSeries[i]) > 0 && len(aggregatedSeries[j]) > 0 {
return *aggregatedSeries[i][0].Value < *aggregatedSeries[j][0].Value
} else if len(aggregatedSeries[j]) > 0 {
return true
}
return false
})
if order == "desc" {
reverseSeries := make([]*TimeSeriesData, len(series))
for i := 0; i < len(series); i++ {
reverseSeries[i] = series[len(series)-1-i]
}
series = reverseSeries
}
return series
}

View File

@@ -145,33 +145,6 @@ func Filter(series []*TimeSeriesData, n int, order string, aggFunc AggFunc) []*T
return filteredSeries
}
func SortBy(series []*TimeSeriesData, order string, aggFunc AggFunc) []*TimeSeriesData {
aggregatedSeries := make([]TimeSeries, len(series))
for i, s := range series {
aggregatedSeries[i] = s.TS.GroupByRange(aggFunc)
}
// Sort by aggregated value
sort.Slice(series, func(i, j int) bool {
if len(aggregatedSeries[i]) > 0 && len(aggregatedSeries[j]) > 0 {
return *aggregatedSeries[i][0].Value < *aggregatedSeries[j][0].Value
} else if len(aggregatedSeries[j]) > 0 {
return true
}
return false
})
if order == "desc" {
reverseSeries := make([]*TimeSeriesData, len(series))
for i := 0; i < len(series); i++ {
reverseSeries[i] = series[len(series)-1-i]
}
series = reverseSeries
}
return series
}
func AggregateBy(series []*TimeSeriesData, interval time.Duration, aggFunc AggFunc) *TimeSeriesData {
aggregatedSeries := NewTimeSeries()