Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tpl/math: Allow variadic math functions to take slice args, add math.Product, math.Sum #11091

Merged
merged 2 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 73 additions & 36 deletions tpl/math/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ package math

import (
"errors"
"fmt"
"math"
"reflect"
"sync/atomic"

_math "github.com/gohugoio/hugo/common/math"
Expand All @@ -25,6 +27,7 @@ import (

var (
errMustTwoNumbersError = errors.New("must provide at least two numbers")
errMustOneNumberError = errors.New("must provide at least one number")
)

// New returns a new instance of the math-namespaced template functions.
Expand Down Expand Up @@ -85,48 +88,30 @@ func (ns *Namespace) Log(n any) (float64, error) {
return math.Log(af), nil
}

// Max returns the greater of the multivalued numbers n1 and n2 or more values.
// Max returns the greater of all numbers in inputs. Any slices in inputs are flattened.
func (ns *Namespace) Max(inputs ...any) (maximum float64, err error) {
if len(inputs) < 2 {
err = errMustTwoNumbersError
return
}
var value float64
for index, input := range inputs {
value, err = cast.ToFloat64E(input)
if err != nil {
err = errors.New("Max operator can't be used with non-float value")
return
}
if index == 0 {
maximum = value
continue
}
maximum = math.Max(value, maximum)
}
return
return ns.applyOpToScalarsOrSlices("Max", math.Max, inputs...)
}

// Min returns the smaller of multivalued numbers n1 and n2 or more values.
// Min returns the smaller of all numbers in inputs. Any slices in inputs are flattened.
func (ns *Namespace) Min(inputs ...any) (minimum float64, err error) {
if len(inputs) < 2 {
err = errMustTwoNumbersError
return
return ns.applyOpToScalarsOrSlices("Min", math.Min, inputs...)
}

// Sum returns the sum of all numbers in inputs. Any slices in inputs are flattened.
func (ns *Namespace) Sum(inputs ...any) (sum float64, err error) {
fn := func(x, y float64) float64 {
return x + y
}
var value float64
for index, input := range inputs {
value, err = cast.ToFloat64E(input)
if err != nil {
err = errors.New("Max operator can't be used with non-float value")
return
}
if index == 0 {
minimum = value
continue
}
minimum = math.Min(value, minimum)
return ns.applyOpToScalarsOrSlices("Sum", fn, inputs...)
}

// Product returns the product of all numbers in inputs. Any slices in inputs are flattened.
func (ns *Namespace) Product(inputs ...any) (product float64, err error) {
fn := func(x, y float64) float64 {
return x * y
}
return
return ns.applyOpToScalarsOrSlices("Product", fn, inputs...)
}

// Mod returns n1 % n2.
Expand Down Expand Up @@ -197,6 +182,58 @@ func (ns *Namespace) Sub(inputs ...any) (any, error) {
return ns.doArithmetic(inputs, '-')
}

func (ns *Namespace) applyOpToScalarsOrSlices(opName string, op func(x, y float64) float64, inputs ...any) (result float64, err error) {
var i int
var hasValue bool
for _, input := range inputs {
var values []float64
var isSlice bool
values, isSlice, err = ns.toFloatsE(input)
if err != nil {
err = fmt.Errorf("%s operator can't be used with non-float values", opName)
return
}
hasValue = hasValue || len(values) > 0 || isSlice
for _, value := range values {
i++
if i == 1 {
result = value
continue
}
result = op(result, value)
}
}

if !hasValue {
err = errMustOneNumberError
return
}
return

}

func (ns *Namespace) toFloatsE(v any) ([]float64, bool, error) {
vv := reflect.ValueOf(v)
switch vv.Kind() {
case reflect.Slice, reflect.Array:
var floats []float64
for i := 0; i < vv.Len(); i++ {
f, err := cast.ToFloat64E(vv.Index(i).Interface())
if err != nil {
return nil, true, err
}
floats = append(floats, f)
}
return floats, true, nil
default:
f, err := cast.ToFloat64E(v)
if err != nil {
return nil, false, err
}
return []float64{f}, false, nil
}
}

func (ns *Namespace) doArithmetic(inputs []any, operation rune) (value any, err error) {
if len(inputs) < 2 {
return nil, errMustTwoNumbersError
Expand Down
75 changes: 68 additions & 7 deletions tpl/math/math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,15 +415,21 @@ func TestMax(t *testing.T) {
{[]any{0, 1}, 1.0},
{[]any{1, -1}, 1.0},
{[]any{1, 0}, 1.0},
{[]any{32}, 32.0},
{[]any{1, 1}, 1.0},
{[]any{1.2, 1.23}, 1.23},
{[]any{-1.2, -1.23}, -1.2},
{[]any{0, "a"}, false},
{[]any{"a", 0}, false},
{[]any{"a", "b"}, false},
// miss values
// Issue #11030
{[]any{7, []any{3, 4}}, 7.0},
{[]any{8, []any{3, 12}, 3}, 12.0},
{[]any{[]any{3, 5, 2}}, 5.0},
{[]any{3, []int{3, 6}, 3}, 6.0},
// No values.
{[]any{}, false},
{[]any{0}, false},

// multi values
{[]any{-1, -2, -3}, -1.0},
{[]any{1, 2, 3}, 3.0},
Expand All @@ -436,8 +442,9 @@ func TestMax(t *testing.T) {
continue
}

c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
msg := qt.Commentf("values: %v", test.values)
c.Assert(err, qt.IsNil, msg)
c.Assert(result, qt.Equals, test.expect, msg)
}
}

Expand All @@ -463,14 +470,21 @@ func TestMin(t *testing.T) {
{[]any{1, -1}, -1.0},
{[]any{1, 0}, 0.0},
{[]any{1, 1}, 1.0},
{[]any{2}, 2.0},
{[]any{1.2, 1.23}, 1.2},
{[]any{-1.2, -1.23}, -1.23},
{[]any{0, "a"}, false},
{[]any{"a", 0}, false},
{[]any{"a", "b"}, false},
// miss values
// Issue #11030
{[]any{1, []any{3, 4}}, 1.0},
{[]any{8, []any{3, 2}, 3}, 2.0},
{[]any{[]any{3, 2, 2}}, 2.0},
{[]any{8, []int{3, 2}, 3}, 2.0},

// No values.
{[]any{}, false},
{[]any{0}, false},

// multi values
{[]any{-1, -2, -3}, -3.0},
{[]any{1, 2, 3}, 1.0},
Expand All @@ -484,7 +498,54 @@ func TestMin(t *testing.T) {
continue
}

c.Assert(err, qt.IsNil)
c.Assert(err, qt.IsNil, qt.Commentf("values: %v", test.values))
c.Assert(result, qt.Equals, test.expect)
}
}

func TestSum(t *testing.T) {
t.Parallel()
c := qt.New(t)

ns := New()

mustSum := func(values ...any) any {
result, err := ns.Sum(values...)
c.Assert(err, qt.IsNil)
return result
}

c.Assert(mustSum(1, 2, 3), qt.Equals, 6.0)
c.Assert(mustSum(1, 2, 3.0), qt.Equals, 6.0)
c.Assert(mustSum(1, 2, []any{3, 4}), qt.Equals, 10.0)
c.Assert(mustSum(23), qt.Equals, 23.0)
c.Assert(mustSum([]any{23}), qt.Equals, 23.0)
c.Assert(mustSum([]any{}), qt.Equals, 0.0)

_, err := ns.Sum()
c.Assert(err, qt.Not(qt.IsNil))

}

func TestProduct(t *testing.T) {
t.Parallel()
c := qt.New(t)

ns := New()

mustProduct := func(values ...any) any {
result, err := ns.Product(values...)
c.Assert(err, qt.IsNil)
return result
}

c.Assert(mustProduct(2, 2, 3), qt.Equals, 12.0)
c.Assert(mustProduct(1, 2, 3.0), qt.Equals, 6.0)
c.Assert(mustProduct(1, 2, []any{3, 4}), qt.Equals, 24.0)
c.Assert(mustProduct(3.0), qt.Equals, 3.0)
c.Assert(mustProduct([]string{}), qt.Equals, 0.0)

_, err := ns.Product()
c.Assert(err, qt.Not(qt.IsNil))

}
Loading