-
Notifications
You must be signed in to change notification settings - Fork 31
/
aggregate.go
74 lines (63 loc) · 1.39 KB
/
aggregate.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
package types
import (
"fmt"
"math"
"strconv"
"github.com/tidwall/gjson"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var (
router funcRouter
)
type ArgsType = gjson.Result
type funcRouter map[string]Aggregate
type Aggregate func(args []ArgsType) string
func init() {
router = make(funcRouter)
_ = RegisterAggregateFunc("max", Max)
_ = RegisterAggregateFunc("min", Min)
_ = RegisterAggregateFunc("avg", Avg)
}
func GetAggregateFunc(methodNm string) (Aggregate, error) {
fun, ok := router[methodNm]
if !ok {
return nil, sdkerrors.Wrapf(ErrNotRegisterFunc, methodNm)
}
return fun, nil
}
func RegisterAggregateFunc(methodNm string, fun Aggregate) error {
_, ok := router[methodNm]
if ok {
return fmt.Errorf("%s has existed", methodNm)
}
router[methodNm] = fun
return nil
}
func Max(data []ArgsType) string {
var maxNumber = math.SmallestNonzeroFloat64
for _, d := range data {
f := d.Float()
if maxNumber < f {
maxNumber = f
}
}
return strconv.FormatFloat(maxNumber, 'f', 8, 64)
}
func Min(data []ArgsType) string {
var minNum = math.MaxFloat64
for _, d := range data {
f := d.Float()
if minNum > d.Float() {
minNum = f
}
}
return strconv.FormatFloat(minNum, 'f', 8, 64)
}
func Avg(data []ArgsType) string {
var total = 0.0
for _, d := range data {
f := d.Float()
total += f
}
return strconv.FormatFloat(total/float64(len(data)), 'f', 8, 64)
}