github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/remove_value.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  // REMOVE_VALUE returns a new array with removed all occurrences of value in a given array.
    12  // Optionally with a limit to the number of removals.
    13  // @param {Any[]} array - Source array.
    14  // @param {Any} value - Target value.
    15  // @param {Int} [limit] - A limit to the number of removals.
    16  // @return {Any[]} - A new array with removed all occurrences of value in a given array.
    17  func RemoveValue(_ context.Context, args ...core.Value) (core.Value, error) {
    18  	err := core.ValidateArgs(args, 2, 3)
    19  
    20  	if err != nil {
    21  		return values.None, err
    22  	}
    23  
    24  	err = core.ValidateType(args[0], types.Array)
    25  
    26  	if err != nil {
    27  		return values.None, err
    28  	}
    29  
    30  	arr := args[0].(*values.Array)
    31  	value := args[1]
    32  	limit := -1
    33  
    34  	if len(args) > 2 {
    35  		err = core.ValidateType(args[2], types.Int)
    36  
    37  		if err != nil {
    38  			return values.None, err
    39  		}
    40  
    41  		limit = int(args[2].(values.Int))
    42  	}
    43  
    44  	result := values.NewArray(int(arr.Length()))
    45  
    46  	counter := 0
    47  	arr.ForEach(func(item core.Value, idx int) bool {
    48  		remove := item.Compare(value) == 0
    49  
    50  		if remove {
    51  			if counter == limit {
    52  				result.Push(item)
    53  			}
    54  
    55  			counter++
    56  		} else {
    57  			result.Push(item)
    58  		}
    59  
    60  		return true
    61  	})
    62  
    63  	return result, nil
    64  }