-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcustom_operator_test.go
65 lines (54 loc) · 1.3 KB
/
custom_operator_test.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
package jsonlogic_test
import (
"encoding/json"
"errors"
"fmt"
"github.com/HuanTeng/go-jsonlogic"
)
// gcd operator
type gcd struct{}
// Operate implements `jsonlogic.Operator`
func (gcd) Operate(applier jsonlogic.LogicApplier, data jsonlogic.DataType, params []jsonlogic.RuleType) (jsonlogic.DataType, error) {
if len(params) != 2 {
return nil, errors.New("only support 2 params")
}
var (
p0, p1 interface{}
err error
)
// apply jsonlogic to each parameters recursively
if p0, err = applier.Apply(params[0], data); err != nil {
return nil, err
}
if p1, err = applier.Apply(params[1], data); err != nil {
return nil, err
}
p0f, ok0 := p0.(float64)
p1f, ok1 := p1.(float64)
if !ok0 || !ok1 {
return nil, errors.New("params should be numbers")
}
// recursive GCD function
var gcdFunc func(a int, b int) int
gcdFunc = func(a int, b int) int {
if b == 0 {
return a
}
return gcdFunc(b, a%b)
}
out := gcdFunc(int(p0f), int(p1f))
// to output a number, always use float64
return float64(out), nil
}
func ExampleOperator() {
jl := jsonlogic.NewJSONLogic()
jl.AddOperation("gcd", gcd{})
var rule interface{}
json.Unmarshal([]byte(`{"gcd": [{"+": [14, 1]}, 25]}`), &rule)
got, err := jl.Apply(rule, nil)
if err != nil {
// handle error
}
fmt.Println(got)
// Output: 5
}