-
Notifications
You must be signed in to change notification settings - Fork 1
/
unit_rule.go
102 lines (93 loc) · 1.97 KB
/
unit_rule.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package rule
import (
"strconv"
)
const (
eq = iota
neq = iota
gt = iota
gte = iota
lt = iota
lte = iota
)
// Rule 规则
type Rule func(c Context) (bool, error)
// Ruler 拥有规则
type Ruler interface {
Rule(c Context) (bool, error)
}
// Negate 对规则进行否运算
func Negate(r Ruler) Ruler {
negateRule := func(c Context) (bool, error) {
result, err := r.Rule(c)
if err != nil {
return false, err
}
return !result, nil
}
return NewUnitRuler(negateRule)
}
func NewUnitRuler(rule Rule) *UnitRuler {
return &UnitRuler{
rule: rule,
}
}
type UnitRuler struct {
rule Rule
}
func (r *UnitRuler) Rule(c Context) (bool, error) {
return r.rule(c)
}
func NewComparatorRule(path string, op int, value float64) (*UnitRuler, error) {
switch op {
case eq:
return NewUnitRuler(func(c Context) (bool, error) {
actual, err := c.PluckFloat64(path)
if err != nil {
return false, err
}
return actual == value, nil
}), nil
case neq:
return NewUnitRuler(func(c Context) (bool, error) {
actual, err := c.PluckFloat64(path)
if err != nil {
return false, err
}
return actual != value, nil
}), nil
case gt:
return NewUnitRuler(func(c Context) (bool, error) {
actual, err := c.PluckFloat64(path)
if err != nil {
return false, err
}
return actual > value, nil
}), nil
case gte:
return NewUnitRuler(func(c Context) (bool, error) {
actual, err := c.PluckFloat64(path)
if err != nil {
return false, err
}
return actual >= value, nil
}), nil
case lt:
return NewUnitRuler(func(c Context) (bool, error) {
actual, err := c.PluckFloat64(path)
if err != nil {
return false, err
}
return actual < value, nil
}), nil
case lte:
return NewUnitRuler(func(c Context) (bool, error) {
actual, err := c.PluckFloat64(path)
if err != nil {
return false, err
}
return actual <= value, nil
}), nil
}
return nil, newArgError("arg error: operation " + strconv.Itoa(op) + " is not allowed")
}