github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/path/join.go (about)

     1  package path
     2  
     3  import (
     4  	"context"
     5  	"path"
     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  // JOIN joins any number of path elements into a single path, separating them with slashes.
    13  // @param {String, repeated | String[]} elements - The path elements
    14  // @return {String} - Single path from the given elements.
    15  func Join(_ context.Context, args ...core.Value) (core.Value, error) {
    16  
    17  	argsCount := len(args)
    18  	if argsCount == 0 {
    19  		return values.EmptyString, nil
    20  	}
    21  
    22  	arr := &values.Array{}
    23  
    24  	if argsCount != 1 && args[0].Type() != types.Array {
    25  		arr = values.NewArrayWith(args...)
    26  	} else {
    27  		arr = args[0].(*values.Array)
    28  	}
    29  
    30  	elems := make([]string, arr.Length())
    31  
    32  	for idx := values.NewInt(0); idx < arr.Length(); idx++ {
    33  		arrElem := arr.Get(idx)
    34  		err := core.ValidateType(arrElem, types.String)
    35  
    36  		if err != nil {
    37  			return values.None, err
    38  		}
    39  
    40  		elems[idx] = arrElem.String()
    41  	}
    42  
    43  	return values.NewString(path.Join(elems...)), nil
    44  }