Skip to content

Commit

Permalink
✨ feat: math - add new util func for compare value
Browse files Browse the repository at this point in the history
- Max()
- SwapMax()
  • Loading branch information
inhere committed Jan 21, 2023
1 parent d0dade8 commit 176923b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
22 changes: 19 additions & 3 deletions mathutil/mathutil.go
Expand Up @@ -7,9 +7,20 @@ import (
"github.com/gookit/goutil/comdef"
)

// MaxFloat compare and return max value
func MaxFloat(x, y float64) float64 {
return math.Max(x, y)
// Max compare two value and return max value
func Max[T comdef.XintOrFloat](x, y T) T {
if x > y {
return x
}
return y
}

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

// MaxInt compare and return max value
Expand Down Expand Up @@ -44,6 +55,11 @@ func SwapMaxI64(x, y int64) (int64, int64) {
return y, x
}

// MaxFloat compare and return max value
func MaxFloat(x, y float64) float64 {
return math.Max(x, y)
}

// OrElse return s OR nv(new-value) on s is empty
func OrElse[T comdef.XintOrFloat](in, nv T) T {
if in != 0 {
Expand Down
11 changes: 10 additions & 1 deletion mathutil/mathutil_test.go
Expand Up @@ -9,17 +9,26 @@ import (

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

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))

assert.Eq(t, 3, mathutil.Max[int](3, 2))
assert.Eq(t, int64(3), mathutil.Max[int64](3, 2))
assert.Eq(t, int64(3), mathutil.Max(int64(3), int64(2)))
}

func TestSwapMaxInt(t *testing.T) {
x, y := mathutil.SwapMaxInt(2, 34)
x, y := mathutil.SwapMax(2, 34)
assert.Eq(t, 34, x)
assert.Eq(t, 2, y)

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

Expand Down

0 comments on commit 176923b

Please sign in to comment.