Skip to content

Commit

Permalink
add slice sum
Browse files Browse the repository at this point in the history
  • Loading branch information
jcdan3 committed Sep 2, 2022
1 parent bdecc97 commit 6050b0a
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 @@ -67,3 +67,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 @@ -71,3 +71,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 6050b0a

Please sign in to comment.