github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/append.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  // APPEND appends a new item to an array and returns a new array with a given element.
    12  // If “uniqueOnly“ is set to true, then will add the item only if it's unique.
    13  // @param {Any[]} arr - Target array.
    14  // @param {Any} item - Target value to add.
    15  // @return {Any[]} - New array.
    16  func Append(_ 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  	arg := args[1]
    31  	unique := values.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  		unique = args[2].(values.Boolean)
    41  	}
    42  
    43  	next := values.NewArray(int(arr.Length()) + 1)
    44  
    45  	if !unique {
    46  		arr.ForEach(func(item core.Value, idx int) bool {
    47  			next.Push(item)
    48  
    49  			return true
    50  		})
    51  
    52  		next.Push(arg)
    53  
    54  		return next, nil
    55  	}
    56  
    57  	hasDuplicate := false
    58  
    59  	arr.ForEach(func(item core.Value, idx int) bool {
    60  		next.Push(item)
    61  
    62  		if !hasDuplicate {
    63  			hasDuplicate = item.Compare(arg) == 0
    64  		}
    65  
    66  		return true
    67  	})
    68  
    69  	if !hasDuplicate {
    70  		next.Push(arg)
    71  	}
    72  
    73  	return next, nil
    74  }