Skip to content

Commit

Permalink
Add mathutil (#267)
Browse files Browse the repository at this point in the history
Co-authored-by: Jordan Krage <[email protected]>
Co-authored-by: Dmytro Haidashenko <[email protected]>
  • Loading branch information
3 people authored and ettec committed Mar 28, 2024
1 parent d971098 commit 3f3a4eb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pkg/utils/mathutil/mathutil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package mathutil

import "golang.org/x/exp/constraints"

func Max[V constraints.Ordered](first V, vals ...V) V {
max := first
for _, v := range vals {
if v > max {
max = v
}
}
return max
}

func Min[V constraints.Ordered](first V, vals ...V) V {
min := first
for _, v := range vals {
if v < min {
min = v
}
}
return min
}
33 changes: 33 additions & 0 deletions pkg/utils/mathutil/mathutil_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package mathutil

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestMax(t *testing.T) {
// Happy path
assert.Equal(t, 3, Max(3, 2, 1))
// Single element
assert.Equal(t, 3, Max(3))
// Signed
assert.Equal(t, -1, Max(-2, -1))
// Uint64
assert.Equal(t, uint64(2), Max(uint64(0), uint64(2)))
// String
assert.Equal(t, "c", Max("a", []string{"b", "c"}...))
}

func TestMin(t *testing.T) {
// Happy path
assert.Equal(t, 1, Min(3, 2, 1))
// Single element
assert.Equal(t, 3, Min(3))
// Signed
assert.Equal(t, -2, Min(-2, -1))
// Uint64
assert.Equal(t, uint64(0), Min(uint64(0), uint64(2)))
// String
assert.Equal(t, "a", Min("a", []string{"b", "c"}...))
}

0 comments on commit 3f3a4eb

Please sign in to comment.