Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Avg function to slice #441

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,16 @@ func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(i

return true
}

// Avg returns the average value of given numbers
// Play: https://go.dev/play/p/2sRbBlcYSHK
func Avg(collection []int) int {
length := len(collection)
total := 0

for _, num := range collection {
total += num
}

return total / length
}
10 changes: 10 additions & 0 deletions slice_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,3 +456,13 @@ func ExampleIsSortedByKey() {

// Output: true
}

func ExampleAvg() {
numbers := []int{1, 2, 3, 4, 5}

result := Avg(numbers)

fmt.Printf("%v", result)

// Output: 3
}
12 changes: 10 additions & 2 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func TestAssociate(t *testing.T) {

func TestSliceToMap(t *testing.T) {
t.Parallel()

type foo struct {
baz string
bar int
Expand Down Expand Up @@ -626,7 +626,7 @@ func TestSlice(t *testing.T) {
out16 := Slice(in, -10, 1)
out17 := Slice(in, -1, 3)
out18 := Slice(in, -10, 7)

is.Equal([]int{}, out1)
is.Equal([]int{0}, out2)
is.Equal([]int{0, 1, 2, 3, 4}, out3)
Expand Down Expand Up @@ -759,3 +759,11 @@ func TestIsSortedByKey(t *testing.T) {
return ret
}))
}

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

is.Equal(Avg([]int{1, 2, 3, 4, 5}), 3)
is.Equal(Avg([]int{10, 20, 30, 40, 50}), 30)
}