github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/operators/in.go (about)

     1  package operators
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/runtime/core"
     7  	"github.com/MontFerret/ferret/pkg/runtime/values"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
     9  )
    10  
    11  type InOperator struct {
    12  	*baseOperator
    13  	negate bool
    14  }
    15  
    16  func NewInOperator(
    17  	src core.SourceMap,
    18  	left core.Expression,
    19  	right core.Expression,
    20  	negate bool,
    21  ) (*InOperator, error) {
    22  	if left == nil {
    23  		return nil, core.Error(core.ErrMissedArgument, "left expression")
    24  	}
    25  
    26  	if right == nil {
    27  		return nil, core.Error(core.ErrMissedArgument, "right expression")
    28  	}
    29  
    30  	return &InOperator{&baseOperator{src, left, right}, negate}, nil
    31  }
    32  
    33  func (operator *InOperator) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
    34  	left, err := operator.left.Exec(ctx, scope)
    35  
    36  	if err != nil {
    37  		return values.False, core.SourceError(operator.src, err)
    38  	}
    39  
    40  	right, err := operator.right.Exec(ctx, scope)
    41  
    42  	if err != nil {
    43  		return values.False, core.SourceError(operator.src, err)
    44  	}
    45  
    46  	return operator.Eval(ctx, left, right)
    47  }
    48  
    49  func (operator *InOperator) Eval(_ context.Context, left, right core.Value) (core.Value, error) {
    50  	err := core.ValidateType(right, types.Array)
    51  
    52  	if err != nil {
    53  		// TODO: Return the error? AQL just returns false
    54  		return values.False, nil
    55  	}
    56  
    57  	arr := right.(*values.Array)
    58  	found := arr.IndexOf(left) > -1
    59  
    60  	if operator.negate {
    61  		return values.NewBoolean(!found), nil
    62  	}
    63  
    64  	return values.NewBoolean(found), nil
    65  }