-
Notifications
You must be signed in to change notification settings - Fork 9
/
expression.go
48 lines (37 loc) · 912 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
package utils
import (
"github.com/PxyUp/fitter/pkg/builder"
"github.com/expr-lang/expr"
)
const (
fitterResultRef = "fRes"
fitterIndexRef = "fIndex"
)
var (
defEnv = map[string]interface{}{}
)
func extendEnv(env map[string]interface{}, result builder.Jsonable, index *uint32) map[string]interface{} {
kv := make(map[string]interface{})
for k, v := range env {
kv[k] = v
}
if result != nil {
kv[fitterResultRef] = result.Raw()
}
if index != nil {
kv[fitterIndexRef] = *index
}
return kv
}
func ProcessExpression(expression string, result builder.Jsonable, index *uint32, input builder.Jsonable) (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
}