forked from air-iot/jsonlogic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vars.go
110 lines (82 loc) · 1.65 KB
/
vars.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
109
110
package jsonlogic
import (
"reflect"
"strings"
)
func solveVars(values, data interface{}) interface{} {
if isMap(values) {
logic := map[string]interface{}{}
for key, value := range values.(map[string]interface{}) {
if key == "var" {
if value == "" || strings.HasPrefix(value.(string), ".") {
logic["var"] = value
continue
}
val := getVar(value, data)
if val != nil {
return val
}
logic["var"] = value
} else {
logic[key] = solveVars(value, data)
}
}
return interface{}(logic)
}
if isSlice(values) {
logic := []interface{}{}
for _, value := range values.([]interface{}) {
logic = append(logic, solveVars(value, data))
}
return logic
}
return values
}
func getVar(value, data interface{}) interface{} {
if value == nil {
return data
}
if isString(value) && toString(value) == "" {
return data
}
if isNumber(value) {
value = toString(value)
}
var _default interface{}
if isSlice(value) { // syntax sugar
length := reflect.ValueOf(value).Len()
if length == 0 {
return data
}
if length == 2 {
_default = value.([]interface{})[1]
}
value = value.([]interface{})[0].(string)
}
if data == nil {
return _default
}
parts := strings.Split(value.(string), ".")
var _value interface{}
for _, part := range parts {
if part == "" {
continue
}
if toNumber(part) > 0 {
_value = data.([]interface{})[int(toNumber(part))]
} else {
_value = data.(map[string]interface{})[part]
}
if _value == nil {
return _default
}
if isPrimitive(_value) {
continue
}
data = _value
}
if _value == nil {
return _default
}
return _value
}