github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/strings/concat.go (about) 1 package strings 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 // CONCAT concatenates one or more instances of String, or an Array. 12 // @param {String, repeated | String[]} src - The source string / array. 13 // @return {String} - A string value. 14 func Concat(_ context.Context, args ...core.Value) (core.Value, error) { 15 err := core.ValidateArgs(args, 1, core.MaxArgs) 16 17 if err != nil { 18 return values.EmptyString, err 19 } 20 21 argsCount := len(args) 22 23 res := values.EmptyString 24 25 if argsCount == 1 && args[0].Type() == types.Array { 26 arr := args[0].(*values.Array) 27 28 arr.ForEach(func(value core.Value, _ int) bool { 29 res = res.Concat(value) 30 31 return true 32 }) 33 34 return res, nil 35 } 36 37 for _, str := range args { 38 res = res.Concat(str) 39 } 40 41 return res, nil 42 } 43 44 // CONCAT_SEPARATOR concatenates one or more instances of String, or an Array with a given separator. 45 // @param {String} separator - The separator string. 46 // @param {String, repeated | String[]} src - The source string / array. 47 // @return {String} - Concatenated string. 48 func ConcatWithSeparator(_ context.Context, args ...core.Value) (core.Value, error) { 49 err := core.ValidateArgs(args, 2, core.MaxArgs) 50 51 if err != nil { 52 return values.EmptyString, err 53 } 54 55 separator := args[0] 56 57 if separator.Type() != types.String { 58 separator = values.NewString(separator.String()) 59 } 60 61 res := values.EmptyString 62 63 for idx, arg := range args[1:] { 64 if arg.Type() != types.Array { 65 if arg.Type() != types.None { 66 if idx > 0 { 67 res = res.Concat(separator) 68 } 69 70 res = res.Concat(arg) 71 } 72 } else { 73 arr := arg.(*values.Array) 74 75 arr.ForEach(func(value core.Value, idx int) bool { 76 if value.Type() != types.None { 77 if idx > 0 { 78 res = res.Concat(separator) 79 } 80 81 res = res.Concat(value) 82 } 83 84 return true 85 }) 86 } 87 } 88 89 return res, nil 90 }