-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathexample_function_test.go
115 lines (100 loc) · 2.12 KB
/
example_function_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
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
package evalfilter
import (
"fmt"
"github.com/skx/evalfilter/v2/object"
)
// ExampleExample demonstrates how you can add a custom function
// to your host-application, which is available to filter scripts.
//
// In this example we add the function `length`, which will calculate the
// length of strings, or the contents of fields, and make it available
// to the scripting-environment.
//
// We use this function to output only those users with names greater
// than four characters in length.
//
func ExampleExample() {
//
// This is the structure our script will operate upon.
//
type Person struct {
Name string
Age int
}
//
// Here is a list of people.
//
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
//
// We'll run this script against each entry in the list
//
script := `
//
// Example filter - we only care about people with "long" names.
//
if ( length(Name) > 4 ) { return true ; }
// Since we return false the caller will know to ignore people here.
return false;
`
//
// Create the evaluator
//
eval := New(script)
//
// Prepare the evaluator.
//
err := eval.Prepare()
if err != nil {
fmt.Printf("Failed to compile the code:%s\n", err.Error())
return
}
//
// Helper function to calculate the length of a string.
//
// Note that we receive a variable number of arguments, for
// simplicity we only calculate the length of the first.
//
// Also note that the function `len` does this job, and is
// built-in and already available.
//
// This is just an example :)
//
eval.AddFunction("length",
func(args []object.Object) object.Object {
sum := 0
for _, e := range args {
sum += len(e.Inspect())
}
return &object.Integer{Value: int64(sum)}
})
//
// Process each person.
//
for _, entry := range people {
//
// Call the filter
//
res, err := eval.Run(entry)
//
// Error-detection is important (!)
//
if err != nil {
panic(err)
}
//
// We only care about the people for whom the filter
// returned `true`.
//
if res {
fmt.Printf("%v\n", entry)
}
}
// Output:
// {Michael 17}
// {Jenny 26}
}