From c11d63c2e2e3976392d238ad75b54c2f7703e223 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Thu, 8 Jun 2023 16:18:25 +0800 Subject: [PATCH] feat: add Sum --- mathutil/mathutil.go | 12 ++++++++++++ mathutil/mathutil_exmaple_test.go | 12 ++++++++++++ mathutil/mathutil_test.go | 7 +++++++ 3 files changed, 31 insertions(+) diff --git a/mathutil/mathutil.go b/mathutil/mathutil.go index 458ce19..8fc469e 100644 --- a/mathutil/mathutil.go +++ b/mathutil/mathutil.go @@ -172,6 +172,18 @@ func MinBy[T any](slice []T, comparator func(T, T) bool) T { 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. // Play: https://go.dev/play/p/Vv7LBwER-pz func Average[T constraints.Integer | constraints.Float](numbers ...T) T { diff --git a/mathutil/mathutil_exmaple_test.go b/mathutil/mathutil_exmaple_test.go index c254700..f969754 100644 --- a/mathutil/mathutil_exmaple_test.go +++ b/mathutil/mathutil_exmaple_test.go @@ -122,6 +122,18 @@ func ExampleAverage() { // 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() { result1 := Max(1, 2, 3) result2 := Max(1.2, 1.4, 1.1, 1.4) diff --git a/mathutil/mathutil_test.go b/mathutil/mathutil_test.go index c3c8b70..b325667 100644 --- a/mathutil/mathutil_test.go +++ b/mathutil/mathutil_test.go @@ -82,6 +82,13 @@ func TestAverage(t *testing.T) { 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) { assert := internal.NewAssert(t, "TestMax")