Skip to content

Commit

Permalink
Adding Mean and MeanBy (#414)
Browse files Browse the repository at this point in the history
* feat: create Mean for ints and floats

* feat: create MeanBy for ints and floats

* chore: add example tests for mean Mean and MeanBy
  • Loading branch information
usman1100 committed Jun 27, 2024
1 parent 05a9bc9 commit 97074ee
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
20 changes: 20 additions & 0 deletions math.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,23 @@ func SumBy[T any, R constraints.Float | constraints.Integer | constraints.Comple
}
return sum
}

// Mean calculates the mean of a collection of numbers.
func Mean[T constraints.Float | constraints.Integer](collection []T) T {
var length T = T(len(collection))
if length == 0 {
return 0
}
var sum T = Sum(collection)
return sum / length
}

// MeanBy calculates the mean of a collection of numbers using the given return value from the iteration function.
func MeanBy[T any, R constraints.Float | constraints.Integer](collection []T, iteratee func(item T) R) R {
var length R = R(len(collection))
if length == 0 {
return 0
}
var sum R = SumBy(collection, iteratee)
return sum / length
}
18 changes: 18 additions & 0 deletions math_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,21 @@ func ExampleSumBy() {
fmt.Printf("%v", result)
// Output: 6
}

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

result := Mean(list)

fmt.Printf("%v", result)
}

func ExampleMeanBy() {
list := []string{"foo", "bar"}

result := MeanBy(list, func(item string) int {
return len(item)
})

fmt.Printf("%v", result)
}
30 changes: 30 additions & 0 deletions math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,33 @@ func TestSumBy(t *testing.T) {
is.Equal(result4, uint32(0))
is.Equal(result5, complex128(6_6))
}

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

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

is.Equal(result1, float32(3.7250001))
is.Equal(result2, int32(3))
is.Equal(result3, uint32(3))
is.Equal(result4, uint32(0))
}

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

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

is.Equal(result1, float32(3.7250001))
is.Equal(result2, int32(3))
is.Equal(result3, uint32(3))
is.Equal(result4, uint32(0))
}

0 comments on commit 97074ee

Please sign in to comment.