-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy patharrays.go
149 lines (112 loc) · 2.36 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
142
143
144
145
146
147
148
149
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 any) any {
parsed := values.([]any)
var subject any
if isSlice(parsed[0]) {
subject = parsed[0]
}
if isMap(parsed[0]) {
subject = apply(parsed[0], data)
}
result := make([]any, 0)
if subject == nil {
return result
}
logic := solveVars(parsed[1], data)
for _, value := range subject.([]any) {
v := parseValues(logic, value)
if isTrue(v) {
result = append(result, value)
}
}
return result
}
func _map(values, data any) any {
parsed := values.([]any)
var subject any
if isSlice(parsed[0]) {
subject = parsed[0]
}
if isMap(parsed[0]) {
subject = apply(parsed[0], data)
}
result := make([]any, 0)
if subject == nil {
return result
}
logic := solveVars(parsed[1], data)
for _, value := range subject.([]any) {
v := parseValues(logic, value)
if isTrue(v) || isNumber(v) || isBool(v) {
result = append(result, v)
}
}
return result
}
func reduce(values, data any) any {
parsed := values.([]any)
var subject any
if isSlice(parsed[0]) {
subject = parsed[0]
}
if isMap(parsed[0]) {
subject = apply(parsed[0], data)
}
if subject == nil {
return float64(0)
}
var (
accumulator any
valueType string
)
{
initialValue := parsed[2]
if isMap(initialValue) {
initialValue = apply(initialValue, data)
}
if isBool(initialValue) {
accumulator = isTrue(initialValue)
valueType = "bool"
} else if isNumber(initialValue) {
accumulator = toNumber(initialValue)
valueType = "number"
} else if isString(initialValue) {
accumulator = toString(initialValue)
valueType = "string"
} else {
panic(ErrReduceDataType{
dataType: fmt.Sprintf("%T", parsed[2]),
})
}
}
context := map[string]any{
"current": float64(0),
"accumulator": accumulator,
"valueType": valueType,
}
for _, value := range subject.([]any) {
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"]
}