github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/push.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  // PUSH create a new array with appended value.
    12  // @param {Any[]} array - Source array.
    13  // @param {Any} value - Target value.
    14  // @param {Boolean} [unique=False] - Read indicating whether to do uniqueness check.
    15  // @return {Any[]} - A new array with appended value.
    16  func Push(_ 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  	value := args[1]
    31  	uniq := 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  		uniq = args[2].Compare(values.True) == 0
    41  	}
    42  
    43  	result := values.NewArray(int(arr.Length() + 1))
    44  	push := true
    45  
    46  	arr.ForEach(func(item core.Value, idx int) bool {
    47  		if uniq && push {
    48  			push = item.Compare(value) != 0
    49  		}
    50  
    51  		result.Push(item)
    52  
    53  		return true
    54  	})
    55  
    56  	if push {
    57  		result.Push(value)
    58  	}
    59  
    60  	return result, nil
    61  }