Add array sum module
This commit is contained in:
10
arrays/sum.go
Normal file
10
arrays/sum.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
func Sum(numbers []int) int {
|
||||
sum := 0
|
||||
// example: for ... in equivalent, first var has index
|
||||
for _, number := range numbers {
|
||||
sum += number
|
||||
}
|
||||
return sum
|
||||
}
|
||||
27
arrays/sum_test.go
Normal file
27
arrays/sum_test.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSum(t *testing.T) {
|
||||
t.Run("collection of 5 numbers", func(t *testing.T) {
|
||||
numbers := []int{1, 2, 3, 4, 5}
|
||||
|
||||
got := Sum(numbers)
|
||||
want := 15
|
||||
|
||||
if got != want {
|
||||
t.Errorf("got %d want %d given, %v", got, want, numbers)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("collection of any size", func(t *testing.T) {
|
||||
numbers := []int{1, 2, 3}
|
||||
|
||||
got := Sum(numbers)
|
||||
want := 6
|
||||
|
||||
if got != want {
|
||||
t.Errorf("got %d want %d given, %v", got, want, numbers)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user