feat: add Max, Min, and Average function

This commit is contained in:
dudaodong
2022-03-22 10:26:43 +08:00
parent 41613061d5
commit c4b0967623
3 changed files with 54 additions and 0 deletions

View File

@@ -11,3 +11,8 @@ type Comparator interface {
// Descending order: should return 1 -> v1 < v2, 0 -> v1 = v2, -1 -> v1 > v2 // Descending order: should return 1 -> v1 < v2, 0 -> v1 = v2, -1 -> v1 > v2
Compare(v1, v2 any) int Compare(v1, v2 any) int
} }
// Number contains all types of number and uintptr, used for generics constraint
type Number interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64
}

View File

@@ -9,6 +9,8 @@ import (
"math" "math"
"strconv" "strconv"
"strings" "strings"
"github.com/duke-git/lancet/v2/lancetconstraints"
) )
// Exponent calculate x^n // Exponent calculate x^n
@@ -90,3 +92,40 @@ func TruncRound(x float64, n int) float64 {
res, _ := strconv.ParseFloat(newFloat, 64) res, _ := strconv.ParseFloat(newFloat, 64)
return res return res
} }
// Max return max value of params
func Max[T lancetconstraints.Number](numbers ...T) T {
max := numbers[0]
for _, v := range numbers {
if max < v {
max = v
}
}
return max
}
// Min return min value of params
func Min[T lancetconstraints.Number](numbers ...T) T {
min := numbers[0]
for _, v := range numbers {
if min > v {
min = v
}
}
return min
}
// Average return average value of params
func Average[T lancetconstraints.Number](numbers ...T) T {
var sum T
n := T(len(numbers))
for _, v := range numbers {
sum += v
}
return sum / n
}

View File

@@ -70,3 +70,13 @@ func TestTruncRound(t *testing.T) {
assert.Equal(TruncRound(0.125, 3), float64(0.125)) assert.Equal(TruncRound(0.125, 3), float64(0.125))
assert.Equal(TruncRound(33.33333, 2), float64(33.33)) assert.Equal(TruncRound(33.33333, 2), float64(33.33))
} }
func TestAverage(t *testing.T) {
assert := internal.NewAssert(t, "TestAverage")
assert.Equal(Average(0, 0), 0)
assert.Equal(Average(1, 1), 1)
avg := Average(1.2, 1.4)
t.Log(avg)
assert.Equal(1.3, RoundToFloat(avg, 1))
}