mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Sum
This commit is contained in:
@@ -172,6 +172,18 @@ func MinBy[T any](slice []T, comparator func(T, T) bool) T {
|
|||||||
return min
|
return min
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sum return sum of passed numbers.
|
||||||
|
// Play: todo
|
||||||
|
func Sum[T constraints.Integer | constraints.Float](numbers ...T) T {
|
||||||
|
var sum T
|
||||||
|
|
||||||
|
for _, v := range numbers {
|
||||||
|
sum += v
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
|
||||||
// Average return average value of numbers.
|
// Average return average value of numbers.
|
||||||
// Play: https://go.dev/play/p/Vv7LBwER-pz
|
// Play: https://go.dev/play/p/Vv7LBwER-pz
|
||||||
func Average[T constraints.Integer | constraints.Float](numbers ...T) T {
|
func Average[T constraints.Integer | constraints.Float](numbers ...T) T {
|
||||||
|
|||||||
@@ -122,6 +122,18 @@ func ExampleAverage() {
|
|||||||
// 1.3
|
// 1.3
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleSum() {
|
||||||
|
result1 := Sum(1, 2)
|
||||||
|
result2 := Sum(0.1, float64(1))
|
||||||
|
|
||||||
|
fmt.Println(result1)
|
||||||
|
fmt.Println(result2)
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// 3
|
||||||
|
// 1.1
|
||||||
|
}
|
||||||
|
|
||||||
func ExampleMax() {
|
func ExampleMax() {
|
||||||
result1 := Max(1, 2, 3)
|
result1 := Max(1, 2, 3)
|
||||||
result2 := Max(1.2, 1.4, 1.1, 1.4)
|
result2 := Max(1.2, 1.4, 1.1, 1.4)
|
||||||
|
|||||||
@@ -82,6 +82,13 @@ func TestAverage(t *testing.T) {
|
|||||||
assert.Equal(1.3, RoundToFloat(avg, 1))
|
assert.Equal(1.3, RoundToFloat(avg, 1))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSum(t *testing.T) {
|
||||||
|
assert := internal.NewAssert(t, "TestSum")
|
||||||
|
|
||||||
|
assert.Equal(1, Sum(0, 1))
|
||||||
|
assert.Equal(1.1, Sum(0.1, float64(1)))
|
||||||
|
}
|
||||||
|
|
||||||
func TestMax(t *testing.T) {
|
func TestMax(t *testing.T) {
|
||||||
assert := internal.NewAssert(t, "TestMax")
|
assert := internal.NewAssert(t, "TestMax")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user