From 723c361171a0cb600c2f481da68326aa60949968 Mon Sep 17 00:00:00 2001 From: Denis Arh Date: Tue, 30 Mar 2021 13:19:46 +0200 Subject: [PATCH] Use built-in len function for wf exec --- pkg/expr/func_gen.go | 14 ++++++++++++++ pkg/expr/func_gen_test.go | 21 +++++++++++++++++++++ pkg/expr/func_str.go | 5 ----- 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/pkg/expr/func_gen.go b/pkg/expr/func_gen.go index b4f9dcbd8..c211a15c6 100644 --- a/pkg/expr/func_gen.go +++ b/pkg/expr/func_gen.go @@ -12,6 +12,7 @@ func GenericFunctions() []gval.Language { gval.Function("coalesce", coalesce), gval.Function("isEmpty", isEmpty), gval.Function("isNil", isNil), + gval.Function("length", length), } } @@ -25,6 +26,19 @@ func coalesce(aa ...interface{}) interface{} { return nil } +func length(i interface{}) int { + if isEmpty(i) { + return 0 + } + + switch reflect.TypeOf(i).Kind() { + case reflect.Slice, reflect.Array, reflect.Ptr, reflect.Map, reflect.String: + return reflect.ValueOf(i).Len() + } + + return 0 +} + func isNil(i interface{}) bool { if i == nil { return true diff --git a/pkg/expr/func_gen_test.go b/pkg/expr/func_gen_test.go index 4a84145cc..3298a0a07 100644 --- a/pkg/expr/func_gen_test.go +++ b/pkg/expr/func_gen_test.go @@ -87,3 +87,24 @@ func Test_empty(t *testing.T) { req.Equal(tst.expect, isEmpty(tst.value)) } } + +func Test_length(t *testing.T) { + var ( + req = require.New(t) + + tcc = []struct { + len int + value interface{} + }{ + {0, []string{}}, + {0, map[string]string{}}, + {3, "foo"}, + {0, make(chan string)}, + {0, 34234}, + } + ) + + for _, tst := range tcc { + req.Equal(tst.len, length(tst.value)) + } +} diff --git a/pkg/expr/func_str.go b/pkg/expr/func_str.go index c51dee54d..7cc1cbeb2 100644 --- a/pkg/expr/func_str.go +++ b/pkg/expr/func_str.go @@ -15,7 +15,6 @@ func StringFunctions() []gval.Language { gval.Function("trim", strings.TrimSpace), gval.Function("trimLeft", strings.TrimLeft), gval.Function("trimRight", strings.TrimRight), - gval.Function("length", length), gval.Function("toLower", strings.ToLower), gval.Function("toUpper", strings.ToUpper), gval.Function("shortest", shortest), @@ -59,10 +58,6 @@ func longest(f string, aa ...string) string { return f } -func length(s string) int { - return len(s) -} - // title works similarly as strings.ToTitle, with the expception // of uppercasing only the first word in line func title(s string) string {