From 92b2b18b9e05fdf6a66f7dbecfc4259b81c34a25 Mon Sep 17 00:00:00 2001 From: debugtalk Date: Sun, 3 Oct 2021 12:30:53 +0800 Subject: [PATCH] feat: call function without argument --- builtin/function.go | 14 ++++++++++++++ parser.go | 2 +- parser_test.go | 18 +++++++++--------- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/builtin/function.go b/builtin/function.go index 8049a113..12172327 100644 --- a/builtin/function.go +++ b/builtin/function.go @@ -1,15 +1,23 @@ package builtin import ( + "crypto/md5" + "encoding/hex" "math" "math/rand" "time" ) var Functions = map[string]interface{}{ + "get_timestamp": getTimestamp, // call without arguments "sleep": sleep, // call with one argument "gen_random_string": genRandomString, // call with one argument "max": math.Max, // call with two arguments + "md5": MD5, +} + +func getTimestamp() int64 { + return time.Now().UnixNano() / int64(time.Millisecond) } func sleep(nSecs int) { @@ -26,3 +34,9 @@ func genRandomString(n int) string { } return string(b) } + +func MD5(str string) string { + hasher := md5.New() + hasher.Write([]byte(str)) + return hex.EncodeToString(hasher.Sum(nil)) +} diff --git a/parser.go b/parser.go index 661d67c5..ca10c30b 100644 --- a/parser.go +++ b/parser.go @@ -171,7 +171,7 @@ func mergeVariables(variables, overriddenVariables map[string]interface{}) map[s // callFunc call function with arguments // only support return at most one result value -func callFunc(funcName string, arguments []interface{}) (interface{}, error) { +func callFunc(funcName string, arguments ...interface{}) (interface{}, error) { function, ok := builtin.Functions[funcName] if !ok { // function not found diff --git a/parser_test.go b/parser_test.go index 8e4e0540..b1702625 100644 --- a/parser_test.go +++ b/parser_test.go @@ -282,10 +282,14 @@ func TestMergeVariables(t *testing.T) { func TestCallFunction(t *testing.T) { // call function without arguments - funcName := "sleep" - arguments := []interface{}{1} + _, err := callFunc("get_timestamp") + if !assert.Nil(t, err) { + t.Fail() + } + + // call function with one argument timeStart := time.Now() - _, err := callFunc(funcName, arguments) + _, err = callFunc("sleep", 1) if !assert.Nil(t, err) { t.Fail() } @@ -294,9 +298,7 @@ func TestCallFunction(t *testing.T) { } // call function with one argument - funcName = "gen_random_string" - arguments = []interface{}{10} - result, err := callFunc(funcName, arguments) + result, err := callFunc("gen_random_string", 10) if !assert.Nil(t, err) { t.Fail() } @@ -305,9 +307,7 @@ func TestCallFunction(t *testing.T) { } // call function with two argument - funcName = "max" - arguments = []interface{}{float64(10), 9.99} - result, err = callFunc(funcName, arguments) + result, err = callFunc("max", float64(10), 9.99) if !assert.Nil(t, err) { t.Fail() }