Skip to content

Commit

Permalink
add slice sum (#210)
Browse files Browse the repository at this point in the history
Co-authored-by: JC Dansereau <jcdansereau@hortau.com>
  • Loading branch information
jcdan3 and jcdan3 committed Oct 10, 2022
1 parent 330382f commit 6f0207a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
9 changes: 9 additions & 0 deletions math.go
Expand Up @@ -72,3 +72,12 @@ func SumBy[T any, R constraints.Float | constraints.Integer](collection []T, ite
}
return sum
}

// Sums the values in a slice.
func Sum[T constraints.Float | constraints.Integer](collection []T) T {
var sum T = 0
for _, val := range collection {
sum += val
}
return sum
}
14 changes: 14 additions & 0 deletions math_test.go
Expand Up @@ -79,3 +79,17 @@ func TestSumBy(t *testing.T) {
is.Equal(result3, uint32(14))
is.Equal(result4, uint32(0))
}

func TestSum(t *testing.T) {
is := assert.New(t)

result1 := Sum([]float32{2.3, 3.3, 4, 5.3})
result2 := Sum([]int32{2, 3, 4, 5})
result3 := Sum([]uint32{2, 3, 4, 5})
result4 := Sum([]uint32{})

is.Equal(result1, float32(14.900001))
is.Equal(result2, int32(14))
is.Equal(result3, uint32(14))
is.Equal(result4, uint32(0))
}

0 comments on commit 6f0207a

Please sign in to comment.