-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtrigger.go
78 lines (61 loc) · 1.56 KB
/
trigger.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
package module
import (
"strconv"
"strings"
"github.com/alibaba/pairec/v2/recconf"
"github.com/alibaba/pairec/v2/utils"
)
type TriggerItem struct {
Key string
DefaultValue string
Boundaries []int
}
func (tr *TriggerItem) GetValue(feature interface{}) string {
if len(tr.Boundaries) == 0 {
return utils.ToString(feature, tr.DefaultValue)
}
val := utils.ToInt(feature, 0)
index := -1
for i, boundary := range tr.Boundaries {
if val <= boundary {
break
} else {
index = i
}
}
if index == -1 {
return "<=" + strconv.Itoa(tr.Boundaries[0])
} else if index == len(tr.Boundaries)-1 {
return ">" + strconv.Itoa(tr.Boundaries[len(tr.Boundaries)-1])
}
return strconv.Itoa(tr.Boundaries[index]) + "-" + strconv.Itoa(tr.Boundaries[index+1])
}
type Trigger struct {
triggers []*TriggerItem
}
func NewTrigger(triggers []recconf.TriggerConfig) *Trigger {
t := &Trigger{}
for _, trigger := range triggers {
triggerItem := &TriggerItem{
Key: trigger.TriggerKey,
DefaultValue: trigger.DefaultValue,
Boundaries: trigger.Boundaries,
}
if triggerItem.DefaultValue == "" {
triggerItem.DefaultValue = "NULL"
}
t.triggers = append(t.triggers, triggerItem)
}
return t
}
func (t *Trigger) GetValue(features map[string]interface{}) string {
values := make([]string, 0, len(t.triggers))
for _, trigger := range t.triggers {
if val, ok := features[trigger.Key]; ok {
values = append(values, trigger.GetValue(val))
} else {
values = append(values, trigger.DefaultValue)
}
}
return strings.Join(values, "_")
}