forked from MontFerret/ferret
/
concat.go
89 lines (66 loc) · 1.81 KB
/
concat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package strings
import (
"context"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
// Concat concatenates one or more instances of Read, or an Array.
// @params src (String...|Array) - The source string / array.
// @returns String
func Concat(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 1, core.MaxArgs)
if err != nil {
return values.EmptyString, err
}
argsCount := len(args)
res := values.EmptyString
if argsCount == 1 && args[0].Type() == core.ArrayType {
arr := args[0].(*values.Array)
arr.ForEach(func(value core.Value, _ int) bool {
res = res.Concat(value)
return true
})
return res, nil
}
for _, str := range args {
res = res.Concat(str)
}
return res, nil
}
// ConcatWithSeparator concatenates one or more instances of Read, or an Array with a given separator.
// @params separator (string) - The separator string.
// @params src (string...|array) - The source string / array.
// @returns string
func ConcatWithSeparator(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 2, core.MaxArgs)
if err != nil {
return values.EmptyString, err
}
separator := args[0]
if separator.Type() != core.StringType {
separator = values.NewString(separator.String())
}
res := values.EmptyString
for idx, arg := range args[1:] {
if arg.Type() != core.ArrayType {
if arg.Type() != core.NoneType {
if idx > 0 {
res = res.Concat(separator)
}
res = res.Concat(arg)
}
} else {
arr := arg.(*values.Array)
arr.ForEach(func(value core.Value, idx int) bool {
if value.Type() != core.NoneType {
if idx > 0 {
res = res.Concat(separator)
}
res = res.Concat(value)
}
return true
})
}
}
return res, nil
}