From 9d5eaf0c1acc55295f69b07c11b3ab9bc3738085 Mon Sep 17 00:00:00 2001 From: rabbitstack Date: Sat, 25 Jan 2025 22:41:45 +0100 Subject: [PATCH] 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. --- pkg/filter/ql/functions/substr.go | 30 +++++++++++++++----------- pkg/filter/ql/functions/substr_test.go | 8 +++++++ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/pkg/filter/ql/functions/substr.go b/pkg/filter/ql/functions/substr.go index 96b397a24..8899f31dc 100644 --- a/pkg/filter/ql/functions/substr.go +++ b/pkg/filter/ql/functions/substr.go @@ -22,7 +22,7 @@ package functions type Substr struct{} func (f Substr) Call(args []interface{}) (interface{}, bool) { - if len(args) < 3 { + if len(args) < 2 { return false, false } @@ -40,17 +40,23 @@ func (f Substr) Call(args []interface{}) (interface{}, bool) { return false, false } - switch v := args[2].(type) { - case int: - end = v - case int64: - end = int(v) - default: - return false, false - } + if len(args) > 2 { + switch v := args[2].(type) { + case int: + end = v + case int64: + end = int(v) + default: + return false, false + } - if start >= 0 && (end >= start && end < len(s)) { - return s[start:end], true + if start >= 0 && (end >= start && end < len(s)) { + return s[start:end], true + } + } else { + if start >= 0 && start < len(s) { + return s[start:], true + } } return s, true @@ -62,7 +68,7 @@ func (f Substr) Desc() FunctionDesc { Args: []FunctionArgDesc{ {Keyword: "string", Types: []ArgType{Func, Field, BoundField, BoundSegment, BareBoundVariable}, Required: true}, {Keyword: "start", Types: []ArgType{Func, Number}, Required: true}, - {Keyword: "end", Types: []ArgType{Func, Number}, Required: true}, + {Keyword: "end", Types: []ArgType{Func, Number}}, }, } return desc diff --git a/pkg/filter/ql/functions/substr_test.go b/pkg/filter/ql/functions/substr_test.go index 7344ee5f6..767b6c0d9 100644 --- a/pkg/filter/ql/functions/substr_test.go +++ b/pkg/filter/ql/functions/substr_test.go @@ -50,6 +50,14 @@ func TestSubstr(t *testing.T) { []interface{}{"Hello World!", 6, 7}, "W", }, + { + []interface{}{"Hello World!", 6}, + "World!", + }, + { + []interface{}{"Hello World!", 20}, + "Hello World!", + }, } for i, tt := range tests {