github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/strings/split.go (about)

     1  package strings
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // SPLIT splits the given string value into a list of strings, using the separator.
    13  // @param {String} str - The string to split.
    14  // @param {String} separator - The separator.
    15  // @param {Int} limit - Limit the number of split values in the result. If no limit is given, the number of splits returned is not bounded.
    16  // @return {String[]} - Array of strings.
    17  func Split(_ context.Context, args ...core.Value) (core.Value, error) {
    18  	err := core.ValidateArgs(args, 2, 3)
    19  
    20  	if err != nil {
    21  		return values.None, err
    22  	}
    23  
    24  	text := args[0].String()
    25  	separator := args[1].String()
    26  	limit := -1
    27  
    28  	if len(args) > 2 {
    29  		if args[2].Type() == types.Int {
    30  			limit = int(args[2].(values.Int))
    31  		}
    32  	}
    33  
    34  	var strs []string
    35  
    36  	if limit < 0 {
    37  		strs = strings.Split(text, separator)
    38  	} else {
    39  		strs = strings.SplitN(text, separator, limit)
    40  	}
    41  
    42  	arr := values.NewArray(len(strs))
    43  
    44  	for _, str := range strs {
    45  		arr.Push(values.NewString(str))
    46  	}
    47  
    48  	return arr, nil
    49  }