Skip to content

Commit ad606f0

Browse files
committed
chore(function): substr with optional argument
Make the substr function accept the third argument as optional. If the third argument is not given, the string is sliced from the start index to its length.
1 parent c0d730f commit ad606f0

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed

pkg/filter/ql/functions/substr.go

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ package functions
2222
type Substr struct{}
2323

2424
func (f Substr) Call(args []interface{}) (interface{}, bool) {
25-
if len(args) < 3 {
25+
if len(args) < 2 {
2626
return false, false
2727
}
2828

@@ -40,17 +40,23 @@ func (f Substr) Call(args []interface{}) (interface{}, bool) {
4040
return false, false
4141
}
4242

43-
switch v := args[2].(type) {
44-
case int:
45-
end = v
46-
case int64:
47-
end = int(v)
48-
default:
49-
return false, false
50-
}
43+
if len(args) > 2 {
44+
switch v := args[2].(type) {
45+
case int:
46+
end = v
47+
case int64:
48+
end = int(v)
49+
default:
50+
return false, false
51+
}
5152

52-
if start >= 0 && (end >= start && end < len(s)) {
53-
return s[start:end], true
53+
if start >= 0 && (end >= start && end < len(s)) {
54+
return s[start:end], true
55+
}
56+
} else {
57+
if start >= 0 && start < len(s) {
58+
return s[start:], true
59+
}
5460
}
5561

5662
return s, true
@@ -62,7 +68,7 @@ func (f Substr) Desc() FunctionDesc {
6268
Args: []FunctionArgDesc{
6369
{Keyword: "string", Types: []ArgType{Func, Field, BoundField, BoundSegment, BareBoundVariable}, Required: true},
6470
{Keyword: "start", Types: []ArgType{Func, Number}, Required: true},
65-
{Keyword: "end", Types: []ArgType{Func, Number}, Required: true},
71+
{Keyword: "end", Types: []ArgType{Func, Number}},
6672
},
6773
}
6874
return desc

pkg/filter/ql/functions/substr_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ func TestSubstr(t *testing.T) {
5050
[]interface{}{"Hello World!", 6, 7},
5151
"W",
5252
},
53+
{
54+
[]interface{}{"Hello World!", 6},
55+
"World!",
56+
},
57+
{
58+
[]interface{}{"Hello World!", 20},
59+
"Hello World!",
60+
},
5361
}
5462

5563
for i, tt := range tests {

0 commit comments

Comments
 (0)