github.com/MontFerret/ferret@v0.18.0/pkg/runtime/collections/filter.go (about)

     1  package collections
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/runtime/core"
     7  )
     8  
     9  type (
    10  	FilterPredicate func(ctx context.Context, scope *core.Scope) (bool, error)
    11  
    12  	FilterIterator struct {
    13  		values    Iterator
    14  		predicate FilterPredicate
    15  	}
    16  )
    17  
    18  func NewFilterIterator(values Iterator, predicate FilterPredicate) (*FilterIterator, error) {
    19  	if values == nil {
    20  		return nil, core.Error(core.ErrMissedArgument, "result")
    21  	}
    22  
    23  	if predicate == nil {
    24  		return nil, core.Error(core.ErrMissedArgument, "predicate")
    25  	}
    26  
    27  	return &FilterIterator{values: values, predicate: predicate}, nil
    28  }
    29  
    30  func (iterator *FilterIterator) Next(ctx context.Context, scope *core.Scope) (*core.Scope, error) {
    31  	for {
    32  		nextScope, err := iterator.values.Next(ctx, scope.Fork())
    33  
    34  		if err != nil {
    35  			return nil, err
    36  		}
    37  
    38  		take, err := iterator.predicate(ctx, nextScope)
    39  
    40  		if err != nil {
    41  			return nil, err
    42  		}
    43  
    44  		if take {
    45  			return nextScope, nil
    46  		}
    47  	}
    48  }