github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/union.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  // UNION returns the union of all passed arrays.
    12  // @param {Any[], repeated} arrays - List of arrays to combine.
    13  // @return {Any[]} - All array elements combined in a single array, in any order.
    14  func Union(_ context.Context, args ...core.Value) (core.Value, error) {
    15  	err := core.ValidateArgs(args, 2, core.MaxArgs)
    16  
    17  	if err != nil {
    18  		return values.None, err
    19  	}
    20  
    21  	err = core.ValidateType(args[0], types.Array)
    22  
    23  	if err != nil {
    24  		return values.None, err
    25  	}
    26  
    27  	firstArrLen := args[0].(*values.Array).Length()
    28  	result := values.NewArray(len(args) * int(firstArrLen))
    29  
    30  	for _, arg := range args {
    31  		err := core.ValidateType(arg, types.Array)
    32  
    33  		if err != nil {
    34  			return values.None, err
    35  		}
    36  
    37  		arr := arg.(*values.Array)
    38  
    39  		arr.ForEach(func(value core.Value, _ int) bool {
    40  			result.Push(value)
    41  			return true
    42  		})
    43  	}
    44  
    45  	return result, nil
    46  }