From 3554b549410128c149c2927e81abd5c4516e8c6a Mon Sep 17 00:00:00 2001 From: Martin Molnar Date: Fri, 15 Jun 2018 12:42:20 +0200 Subject: [PATCH] add template function to multiply values --- template/functions.go | 1 + template/multiply.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 template/multiply.go diff --git a/template/functions.go b/template/functions.go index 8fa77fb8..2b835fd9 100644 --- a/template/functions.go +++ b/template/functions.go @@ -23,6 +23,7 @@ var funcs functions = make(map[string]functionWithValidator) func init() { funcs.add("timestamp", newTimestampFunc()) + funcs.add("multiply", newMultiplyFunc()) } type functions map[string]functionWithValidator diff --git a/template/multiply.go b/template/multiply.go new file mode 100644 index 00000000..86b82918 --- /dev/null +++ b/template/multiply.go @@ -0,0 +1,36 @@ +package template + +import ( + "fmt" + "strconv" + "text/template/parse" +) + +func newMultiplyFunc() functionWithValidator { + return functionWithValidator{ + function: multiply, + staticValidator: validateMultiplyCall, + } +} + +func multiply(value string, multiplier float64) (float64, error) { + i, err := strconv.ParseFloat(value, 64) + if err != nil { + return 0, err + } + + return i * multiplier, nil +} + +func validateMultiplyCall(cmd *parse.CommandNode) error { + prefix := "syntax error in shift call" + if len(cmd.Args) != 3 { + return fmt.Errorf("%v: expected two parameters, but found %v parameters", prefix, len(cmd.Args)-1) + } + exponentNode, ok := cmd.Args[2].(*parse.NumberNode) + if !ok || !exponentNode.IsFloat { + return fmt.Errorf("%v: unable to parse %v as a float number", prefix, exponentNode.Text) + } + + return nil +}