-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathoption_iter_function_test.go
More file actions
60 lines (54 loc) · 961 Bytes
/
option_iter_function_test.go
File metadata and controls
60 lines (54 loc) · 961 Bytes
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
package gojq_test
import (
"fmt"
"log"
"github.com/itchyny/gojq"
)
// Implementation of range/2 using WithIterFunction option.
type rangeIter struct {
value, max int
}
func (iter *rangeIter) Next() (any, bool) {
if iter.value >= iter.max {
return nil, false
}
v := iter.value
iter.value++
return v, true
}
func ExampleWithIterFunction() {
query, err := gojq.Parse("f(3; 7)")
if err != nil {
log.Fatalln(err)
}
code, err := gojq.Compile(
query,
gojq.WithIterFunction("f", 2, 2, func(_ any, xs []any) gojq.Iter {
if x, ok := xs[0].(int); ok {
if y, ok := xs[1].(int); ok {
return &rangeIter{x, y}
}
}
return gojq.NewIter(fmt.Errorf("f cannot be applied to: %v", xs))
}),
)
if err != nil {
log.Fatalln(err)
}
iter := code.Run(nil)
for {
v, ok := iter.Next()
if !ok {
break
}
if err, ok := v.(error); ok {
log.Fatalln(err)
}
fmt.Printf("%#v\n", v)
}
// Output:
// 3
// 4
// 5
// 6
}