github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/position.go (about)

     1  package arrays
     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  // POSITION returns a value indicating whether an element is contained in array. Optionally returns its position.
    12  // @param {Any[]} array - The source array.
    13  // @param {Any} value - The target value.
    14  // @param {Boolean} [position=False] - Boolean value which indicates whether to return item's position.
    15  // @return {Boolean | Int} - A value indicating whether an element is contained in array.
    16  func Position(_ context.Context, args ...core.Value) (core.Value, error) {
    17  	err := core.ValidateArgs(args, 2, 3)
    18  
    19  	if err != nil {
    20  		return values.None, err
    21  	}
    22  
    23  	err = core.ValidateType(args[0], types.Array)
    24  
    25  	if err != nil {
    26  		return values.None, err
    27  	}
    28  
    29  	arr := args[0].(*values.Array)
    30  	el := args[1]
    31  	retIdx := false
    32  
    33  	if len(args) > 2 {
    34  		err = core.ValidateType(args[2], types.Boolean)
    35  
    36  		if err != nil {
    37  			return values.None, err
    38  		}
    39  
    40  		retIdx = args[2].Compare(values.True) == 0
    41  	}
    42  
    43  	position := arr.IndexOf(el)
    44  
    45  	if !retIdx {
    46  		return values.NewBoolean(position > -1), nil
    47  	}
    48  
    49  	return position, nil
    50  }