-
Notifications
You must be signed in to change notification settings - Fork 9
/
expression.go
75 lines (61 loc) · 1.52 KB
/
expression.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
package utils
import (
"encoding/json"
"github.com/PxyUp/fitter/pkg/builder"
"github.com/expr-lang/expr"
)
const (
fitterResultJsonRef = "fResJson"
fitterResultRef = "fRes"
fitterIndexRef = "fIndex"
fitterResultRaw = "fResRaw"
)
var (
defEnv = map[string]interface{}{
"reverse": func(s []interface{}) []interface{} {
a := make([]interface{}, len(s))
copy(a, s)
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
return a
},
"FNull": builder.NullValue,
"FNil": nil,
"isNull": func(value interface{}) bool {
return builder.NullValue == value
},
}
)
func extendEnv(env map[string]interface{}, result builder.Interfacable, index *uint32) map[string]interface{} {
kv := make(map[string]interface{})
for k, v := range env {
kv[k] = v
}
if result != nil {
kv[fitterResultRaw] = result.Raw()
kv[fitterResultRef] = result.ToInterface()
kv[fitterResultJsonRef] = result.ToJson()
}
if index != nil {
kv[fitterIndexRef] = *index
}
return kv
}
func ProcessExpression(expression string, result builder.Interfacable, index *uint32, input builder.Interfacable) (builder.Interfacable, error) {
env := extendEnv(defEnv, result, index)
program, err := expr.Compile(Format(expression, result, index, input), expr.Env(env))
if err != nil {
return nil, err
}
out, err := expr.Run(program, env)
if err != nil {
return nil, err
}
bb, err := json.Marshal(out)
if err != nil {
return nil, err
}
return builder.ToJsonable(bb), nil
}