-
Notifications
You must be signed in to change notification settings - Fork 9
/
expression.go
50 lines (39 loc) · 1018 Bytes
/
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
package utils
import (
"github.com/PxyUp/fitter/pkg/builder"
"github.com/expr-lang/expr"
)
const (
fitterResultJsonRef = "fResJson"
fitterResultRef = "fRes"
fitterIndexRef = "fIndex"
)
var (
defEnv = map[string]interface{}{}
)
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[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) (interface{}, error) {
env := extendEnv(defEnv, result, index)
program, err := expr.Compile(Format(expression, result, index, input), expr.Env(env))
if err != nil {
return false, err
}
out, err := expr.Run(program, env)
if err != nil {
return false, err
}
return out, nil
}