2018-10-25 03:30:05 +02:00
|
|
|
package collections
|
|
|
|
|
|
|
|
import (
|
2018-10-28 07:45:26 +02:00
|
|
|
"context"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
2018-10-25 03:30:05 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
|
|
)
|
|
|
|
|
|
|
|
type KeyedIterator struct {
|
|
|
|
valVar string
|
|
|
|
keyVar string
|
|
|
|
values KeyedCollection
|
|
|
|
keys []string
|
|
|
|
pos int
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewKeyedIterator(
|
|
|
|
valVar,
|
|
|
|
keyVar string,
|
2018-10-28 07:45:26 +02:00
|
|
|
values KeyedCollection,
|
|
|
|
) (Iterator, error) {
|
|
|
|
if valVar == "" {
|
|
|
|
return nil, core.Error(core.ErrMissedArgument, "value variable")
|
|
|
|
}
|
|
|
|
|
|
|
|
if values == nil {
|
|
|
|
return nil, core.Error(core.ErrMissedArgument, "result")
|
|
|
|
}
|
|
|
|
|
|
|
|
return &KeyedIterator{valVar, keyVar, values, nil, 0}, nil
|
2018-10-25 03:30:05 +02:00
|
|
|
}
|
|
|
|
|
2018-10-28 07:45:26 +02:00
|
|
|
func NewDefaultKeyedIterator(input KeyedCollection) (Iterator, error) {
|
2018-10-25 03:30:05 +02:00
|
|
|
return NewKeyedIterator(DefaultValueVar, DefaultKeyVar, input)
|
|
|
|
}
|
|
|
|
|
2018-10-28 07:45:26 +02:00
|
|
|
func (iterator *KeyedIterator) Next(_ context.Context, scope *core.Scope) (*core.Scope, error) {
|
2018-10-25 03:30:05 +02:00
|
|
|
if iterator.keys == nil {
|
|
|
|
iterator.keys = iterator.values.Keys()
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(iterator.keys) > iterator.pos {
|
|
|
|
key := values.NewString(iterator.keys[iterator.pos])
|
|
|
|
val, _ := iterator.values.Get(key)
|
2018-10-28 07:45:26 +02:00
|
|
|
|
2018-10-25 03:30:05 +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, key); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nextScope, nil
|
2018-10-25 03:30:05 +02:00
|
|
|
}
|
|
|
|
|
2018-10-28 07:45:26 +02:00
|
|
|
return nil, nil
|
2018-10-25 03:30:05 +02:00
|
|
|
}
|