github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/arrays/slice.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  // SLICE returns a new sliced array.
    12  // @param {Any[]} array - Source array.
    13  // @param {Int} start - Start position of extraction.
    14  // @param {Int} [length] - Read indicating how many elements to extract.
    15  // @return {Any[]} - Sliced array.
    16  func Slice(_ 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  	err = core.ValidateType(args[1], types.Int)
    30  
    31  	if err != nil {
    32  		return values.None, err
    33  	}
    34  
    35  	arr := args[0].(*values.Array)
    36  	start := args[1].(values.Int)
    37  	length := values.NewInt(int(arr.Length()))
    38  
    39  	if len(args) > 2 {
    40  		if args[2].Type() == types.Int {
    41  			arg2 := args[2].(values.Int)
    42  
    43  			if arg2 > 0 {
    44  				length = start + args[2].(values.Int)
    45  			}
    46  		}
    47  	}
    48  
    49  	return arr.Slice(start, length), nil
    50  }