From bda082c98c7a0abdb019f12bb21cbaa7b0e8f60e Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Tue, 16 May 2023 19:32:07 +0300 Subject: tpl: Add math.Abs Fixes #10941. --- tpl/math/init.go | 7 +++++++ tpl/math/math.go | 10 ++++++++++ tpl/math/math_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) (limited to 'tpl/math') diff --git a/tpl/math/init.go b/tpl/math/init.go index 67aa95f41..8596ff647 100644 --- a/tpl/math/init.go +++ b/tpl/math/init.go @@ -31,6 +31,13 @@ func init() { Context: func(cctx context.Context, args ...any) (any, error) { return ctx, nil }, } + ns.AddMethodMapping(ctx.Abs, + nil, + [][2]string{ + {"{{ math.Abs -2.1 }}", "2.1"}, + }, + ) + ns.AddMethodMapping(ctx.Add, []string{"add"}, [][2]string{ diff --git a/tpl/math/math.go b/tpl/math/math.go index 67c6d06c5..d73f212a6 100644 --- a/tpl/math/math.go +++ b/tpl/math/math.go @@ -35,6 +35,16 @@ func New() *Namespace { // Namespace provides template functions for the "math" namespace. type Namespace struct{} +// Abs returns the absolute value of n. +func (ns *Namespace) Abs(n any) (float64, error) { + af, err := cast.ToFloat64E(n) + if err != nil { + return 0, errors.New("the math.Abs function requires a numeric argument") + } + + return math.Abs(af), nil +} + // Add adds the multivalued addends n1 and n2 or more values. func (ns *Namespace) Add(inputs ...any) (any, error) { return ns.doArithmetic(inputs, '+') diff --git a/tpl/math/math_test.go b/tpl/math/math_test.go index 3e83405fd..fad86938d 100644 --- a/tpl/math/math_test.go +++ b/tpl/math/math_test.go @@ -63,6 +63,33 @@ func TestBasicNSArithmetic(t *testing.T) { } } +func TestAbs(t *testing.T) { + t.Parallel() + c := qt.New(t) + ns := New() + + for _, test := range []struct { + x any + expect any + }{ + {0.0, 0.0}, + {1.5, 1.5}, + {-1.5, 1.5}, + {-2, 2.0}, + {"abc", false}, + } { + result, err := ns.Abs(test.x) + + if b, ok := test.expect.(bool); ok && !b { + c.Assert(err, qt.Not(qt.IsNil)) + continue + } + + c.Assert(err, qt.IsNil) + c.Assert(result, qt.Equals, test.expect) + } +} + func TestCeil(t *testing.T) { t.Parallel() c := qt.New(t) -- cgit v1.2.3