github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/remove_values.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_VALUES returns a new array with removed all occurrences of values in a given array.
    12  // @param {Any[]} array - Source array.
    13  // @param {Any[]} values - Target values.
    14  // @return {Any[]} - A new array with removed all occurrences of values in a given array.
    15  func RemoveValues(_ context.Context, args ...core.Value) (core.Value, error) {
    16  	err := core.ValidateArgs(args, 2, 2)
    17  
    18  	if err != nil {
    19  		return values.None, err
    20  	}
    21  
    22  	err = core.ValidateType(args[0], types.Array)
    23  
    24  	if err != nil {
    25  		return values.None, err
    26  	}
    27  
    28  	err = core.ValidateType(args[1], types.Array)
    29  
    30  	if err != nil {
    31  		return values.None, err
    32  	}
    33  
    34  	arr := args[0].(*values.Array)
    35  	vals := args[1].(*values.Array)
    36  
    37  	result := values.NewArray(int(arr.Length()))
    38  	lookupTable := make(map[uint64]bool)
    39  
    40  	vals.ForEach(func(value core.Value, idx int) bool {
    41  		lookupTable[value.Hash()] = true
    42  
    43  		return true
    44  	})
    45  
    46  	arr.ForEach(func(value core.Value, idx int) bool {
    47  		h := value.Hash()
    48  
    49  		_, exists := lookupTable[h]
    50  
    51  		if !exists {
    52  			result.Push(value)
    53  		}
    54  
    55  		return true
    56  	})
    57  
    58  	return result, nil
    59  }