1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-29 01:44:23 +02:00
ferret/pkg/runtime/collections/indexed.go

67 lines
1.3 KiB
Go
Raw Normal View History

package collections
import (
2018-10-28 07:45:26 +02:00
"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,
2018-10-28 07:45:26 +02:00
values IndexedCollection,
) (Iterator, error) {
if valVar == "" {
return nil, core.Error(core.ErrMissedArgument, "value variable")
}
2018-10-28 07:45:26 +02:00
if values == nil {
return nil, core.Error(core.ErrMissedArgument, "result")
}
return &IndexedIterator{valVar, keyVar, values, 0}, nil
}
2018-10-28 07:45:26 +02:00
func NewDefaultIndexedIterator(
values IndexedCollection,
) (Iterator, error) {
return NewIndexedIterator(DefaultValueVar, DefaultKeyVar, values)
}
2018-10-28 07:45:26 +02:00
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)
2018-10-28 07:45:26 +02:00
iterator.pos++
2018-10-28 07:45:26 +02:00
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, core.ErrNoMoreData
}