forked from MontFerret/ferret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexed.go
66 lines (52 loc) · 1.3 KB
/
indexed.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
package collections
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
const (
DefaultValueVar = "value"
DefaultKeyVar = "key"
)
type IndexedIterator struct {
valVar string
keyVar string
values IndexedCollection
pos int
}
func NewIndexedIterator(
valVar,
keyVar string,
values IndexedCollection,
) (Iterator, error) {
if valVar == "" {
return nil, core.Error(core.ErrMissedArgument, "value variable")
}
if values == nil {
return nil, core.Error(core.ErrMissedArgument, "result")
}
return &IndexedIterator{valVar, keyVar, values, 0}, nil
}
func NewDefaultIndexedIterator(
values IndexedCollection,
) (Iterator, error) {
return NewIndexedIterator(DefaultValueVar, DefaultKeyVar, values)
}
func (iterator *IndexedIterator) Next(_ context.Context, scope *core.Scope) (*core.Scope, error) {
if int(iterator.values.Length()) > iterator.pos {
idx := values.NewInt(iterator.pos)
val := iterator.values.Get(idx)
iterator.pos++
nextScope := scope.Fork()
if err := nextScope.SetVariable(iterator.valVar, val); err != nil {
return nil, err
}
if iterator.keyVar != "" {
if err := nextScope.SetVariable(iterator.keyVar, idx); err != nil {
return nil, err
}
}
return nextScope, nil
}
return nil, nil
}