Skip to content

Commit

Permalink
✨ feat(math): add new util Min, SwapMin func and add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 22, 2023
1 parent 303b699 commit 19ba2eb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions mathutil/mathutil.go
Expand Up @@ -7,6 +7,14 @@ import (
"github.com/gookit/goutil/comdef"
)

// Min compare two value and return max value
func Min[T comdef.XintOrFloat](x, y T) T {
if x < y {
return x
}
return y
}

// Max compare two value and return max value
func Max[T comdef.XintOrFloat](x, y T) T {
if x > y {
Expand All @@ -15,6 +23,14 @@ func Max[T comdef.XintOrFloat](x, y T) T {
return y
}

// SwapMin compare and always return [min, max] value
func SwapMin[T comdef.XintOrFloat](x, y T) (T, T) {
if x < y {
return x, y
}
return y, x
}

// SwapMax compare and always return [max, min] value
func SwapMax[T comdef.XintOrFloat](x, y T) (T, T) {
if x > y {
Expand Down
19 changes: 19 additions & 0 deletions mathutil/mathutil_test.go
Expand Up @@ -9,12 +9,19 @@ import (

func TestMaxFloat(t *testing.T) {
assert.Eq(t, float64(3), mathutil.MaxFloat(2, 3))
assert.Eq(t, 3.3, mathutil.MaxFloat(2.1, 3.3))

assert.Eq(t, 3.3, mathutil.Max(2.1, 3.3))
assert.Eq(t, 3.3, mathutil.Max(3.3, 2.1))

assert.Eq(t, 2.1, mathutil.Min(2.1, 3.3))
assert.Eq(t, 2.1, mathutil.Min(3.3, 2.1))
}

func TestMaxI64(t *testing.T) {
assert.Eq(t, 3, mathutil.MaxInt(2, 3))
assert.Eq(t, 3, mathutil.MaxInt(3, 2))

assert.Eq(t, int64(3), mathutil.MaxI64(2, 3))
assert.Eq(t, int64(3), mathutil.MaxI64(3, 2))

Expand All @@ -28,6 +35,18 @@ func TestSwapMaxInt(t *testing.T) {
assert.Eq(t, 34, x)
assert.Eq(t, 2, y)

x, y = mathutil.SwapMax(34, 2)
assert.Eq(t, 34, x)
assert.Eq(t, 2, y)

x, y = mathutil.SwapMin(2, 34)
assert.Eq(t, 2, x)
assert.Eq(t, 34, y)

x, y = mathutil.SwapMin(34, 2)
assert.Eq(t, 2, x)
assert.Eq(t, 34, y)

x, y = mathutil.SwapMaxInt(2, 34)
assert.Eq(t, 34, x)
assert.Eq(t, 2, y)
Expand Down

0 comments on commit 19ba2eb

Please sign in to comment.