-
Notifications
You must be signed in to change notification settings - Fork 2
/
operation.go
108 lines (100 loc) · 2.39 KB
/
operation.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
103
104
105
106
107
108
package gisk
import (
"errors"
"github.com/gogf/gf/v2/util/gconv"
"strings"
"sync"
)
// Operation 运算
func Operation(left Value, operator Operator, right Value) (result bool, err error) {
//优先使用用户注册比较符
fun, ok := getOperation(operator)
if ok {
return fun(left, operator, right)
}
switch operator {
case EQ:
result = gconv.String(left.Value) == gconv.String(right.Value)
return
case NEQ:
result = gconv.String(left.Value) != gconv.String(right.Value)
return
case GT:
result = gconv.Float64(left.Value) > gconv.Float64(right.Value)
return
case LT:
result = gconv.Float64(left.Value) < gconv.Float64(right.Value)
return
case GTE:
result = gconv.Float64(left.Value) >= gconv.Float64(right.Value)
return
case LTE:
result = gconv.Float64(left.Value) <= gconv.Float64(right.Value)
return
case IN:
switch right.ValueType {
case MAP:
for _, v := range right.Value.(map[string]interface{}) {
if gconv.String(left.Value) == gconv.String(v) {
result = true
return
}
}
case ARRAY:
for _, v := range right.Value.([]string) {
if gconv.String(left.Value) == gconv.String(v) {
result = true
return
}
}
default:
err = errors.New("IN运算符的右侧必须是数组或map")
}
return
case NOTIN:
switch right.ValueType {
case MAP:
for _, v := range right.Value.(map[interface{}]interface{}) {
if gconv.String(left.Value) == gconv.String(v) {
result = false
return
}
}
case ARRAY:
for _, v := range right.Value.([]string) {
if gconv.String(left.Value) == gconv.String(v) {
result = false
return
}
}
default:
err = errors.New("NOTIN运算符的右侧必须是数组或map")
}
return
case LIKE:
l := gconv.String(left.Value)
r := gconv.String(right.Value)
result = strings.Contains(r, l)
return
case NOTLIKE:
l := gconv.String(left.Value)
r := gconv.String(right.Value)
result = !strings.Contains(r, l)
return
default:
err = errors.New("operator not support")
}
return
}
type OperationFunc func(left Value, operator Operator, right Value) (result bool, err error)
var operationMap sync.Map
func RegisterOperation(name Operator, op OperationFunc) {
operationMap.Store(name, op)
}
func getOperation(name Operator) (OperationFunc, bool) {
op, ok := operationMap.Load(name)
if !ok {
return nil, false
}
return op.(OperationFunc), true
}