github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/pop.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  // POP returns a new array without last element.
    12  // @param {Any[]} array - Target array.
    13  // @return {Any[]} - Copy of an array without last element.
    14  func Pop(_ context.Context, args ...core.Value) (core.Value, error) {
    15  	err := core.ValidateArgs(args, 1, 1)
    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  	arr := args[0].(*values.Array)
    28  
    29  	length := int(arr.Length())
    30  	result := values.NewArray(length)
    31  	lastIdx := length - 1
    32  
    33  	arr.ForEach(func(value core.Value, idx int) bool {
    34  		if idx == lastIdx {
    35  			return false
    36  		}
    37  
    38  		result.Push(value)
    39  
    40  		return true
    41  	})
    42  
    43  	return result, nil
    44  }