diff --git a/cli/test.yaml b/cli/test.yaml index 8b0727f9..c4e5757d 100644 --- a/cli/test.yaml +++ b/cli/test.yaml @@ -2082,6 +2082,63 @@ "rtrimstr({}) cannot be applied to: string (\"x\")" "rtrimstr(\"x\") cannot be applied to: number (10)" +- name: ltrim function + args: + - 'ltrim' + input: | + "" + " \tfoo\n " + "\t\u000b\u000c\u0085\u00a0f\ro\no\u2000\u2001\u200a\u3000" + expected: "\"\"\n\"foo\\n \"\n\"f\\ro\\no\u2000\u2001\u200a\u3000\"\n" + +- name: ltrim function error + args: + - 'try ltrim catch .' + input: '0 [] {}' + expected: | + "ltrim cannot be applied to: number (0)" + "ltrim cannot be applied to: array ([])" + "ltrim cannot be applied to: object ({})" + +- name: rtrim function + args: + - 'rtrim' + input: | + "" + " \tfoo\n " + "\t\u000b\u000c\u0085\u00a0f\ro\no\u2000\u2001\u200a\u3000" + expected: "\"\"\n\" \\tfoo\"\n\"\\t\\u000b\\f\u0085\u00a0f\\ro\\no\"\n" + +- name: rtrim function error + args: + - 'try rtrim catch .' + input: '0 [] {}' + expected: | + "rtrim cannot be applied to: number (0)" + "rtrim cannot be applied to: array ([])" + "rtrim cannot be applied to: object ({})" + +- name: trim function + args: + - 'trim' + input: | + "" + " \tfoo\n " + "\t\u000b\u000c\u0085\u00a0f\ro\no\u2000\u2001\u200a\u3000" + expected: | + "" + "foo" + "f\ro\no" + +- name: trim function error + args: + - 'try trim catch .' + input: '0 [] {}' + expected: | + "trim cannot be applied to: number (0)" + "trim cannot be applied to: array ([])" + "trim cannot be applied to: object ({})" + - name: explode function args: - -c diff --git a/func.go b/func.go index f5319500..d747121b 100644 --- a/func.go +++ b/func.go @@ -15,6 +15,7 @@ import ( "strconv" "strings" "time" + "unicode" "unicode/utf8" "github.com/itchyny/timefmt-go" @@ -70,6 +71,9 @@ func init() { "endswith": argFunc1(funcEndsWith), "ltrimstr": argFunc1(funcLtrimstr), "rtrimstr": argFunc1(funcRtrimstr), + "ltrim": argFunc0(funcLtrim), + "rtrim": argFunc0(funcRtrim), + "trim": argFunc0(funcTrim), "explode": argFunc0(funcExplode), "implode": argFunc0(funcImplode), "split": {argcount1 | argcount2, false, funcSplit}, @@ -702,6 +706,30 @@ func funcRtrimstr(v, x any) any { return strings.TrimSuffix(s, t) } +func funcLtrim(v any) any { + s, ok := v.(string) + if !ok { + return &func0TypeError{"ltrim", v} + } + return strings.TrimLeftFunc(s, unicode.IsSpace) +} + +func funcRtrim(v any) any { + s, ok := v.(string) + if !ok { + return &func0TypeError{"rtrim", v} + } + return strings.TrimRightFunc(s, unicode.IsSpace) +} + +func funcTrim(v any) any { + s, ok := v.(string) + if !ok { + return &func0TypeError{"trim", v} + } + return strings.TrimSpace(s) +} + func funcExplode(v any) any { s, ok := v.(string) if !ok {