-
Notifications
You must be signed in to change notification settings - Fork 47
/
arrays.go
141 lines (106 loc) · 2.38 KB
/
arrays.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package jsonlogic
import "fmt"
type ErrReduceDataType struct {
dataType string
}
func (e ErrReduceDataType) Error() string {
return fmt.Sprintf("The type \"%s\" is not supported", e.dataType)
}
func filter(values, data interface{}) interface{} {
parsed := values.([]interface{})
var subject interface{}
if isSlice(parsed[0]) {
subject = parsed[0]
}
if isMap(parsed[0]) {
subject = apply(parsed[0], data)
}
result := make([]interface{}, 0)
if subject == nil {
return result
}
logic := solveVars(parsed[1], data)
for _, value := range subject.([]interface{}) {
v := parseValues(logic, value)
if isTrue(v) {
result = append(result, value)
}
}
return result
}
func _map(values, data interface{}) interface{} {
parsed := values.([]interface{})
var subject interface{}
if isSlice(parsed[0]) {
subject = parsed[0]
}
if isMap(parsed[0]) {
subject = apply(parsed[0], data)
}
result := make([]interface{}, 0)
if subject == nil {
return result
}
logic := solveVars(parsed[1], data)
for _, value := range subject.([]interface{}) {
v := parseValues(logic, value)
if isTrue(v) || isNumber(v) || isBool(v) {
result = append(result, v)
}
}
return result
}
func reduce(values, data interface{}) interface{} {
parsed := values.([]interface{})
var subject interface{}
if isSlice(parsed[0]) {
subject = parsed[0]
}
if isMap(parsed[0]) {
subject = apply(parsed[0], data)
}
if subject == nil {
return float64(0)
}
var (
accumulator interface{}
valueType string
)
{
if isBool(parsed[2]) {
accumulator = isTrue(parsed[2])
valueType = "bool"
} else if isNumber(parsed[2]) {
accumulator = toNumber(parsed[2])
valueType = "number"
} else if isString(parsed[2]) {
accumulator = toString(parsed[2])
valueType = "string"
} else {
panic(ErrReduceDataType{
dataType: fmt.Sprintf("%T", parsed[2]),
})
}
}
context := map[string]interface{}{
"current": float64(0),
"accumulator": accumulator,
"valueType": valueType,
}
for _, value := range subject.([]interface{}) {
if value == nil {
continue
}
context["current"] = value
v := apply(parsed[1], context)
switch context["valueType"] {
case "bool":
context["accumulator"] = isTrue(v)
case "number":
context["accumulator"] = toNumber(v)
case "string":
context["accumulator"] = toString(v)
}
}
return context["accumulator"]
}