added Reduce method

This commit is contained in:
milarin 2023-03-09 14:34:44 +01:00
parent 55928776b4
commit ab6e6684f8
4 changed files with 31 additions and 3 deletions

4
go.mod
View File

@ -1,3 +1,5 @@
module git.milar.in/milarin/slices
go 1.19
go 1.19
require git.milar.in/milarin/gmath v0.0.3

4
go.sum
View File

@ -1,2 +1,2 @@
git.milar.in/milarin/channel v0.0.7 h1:cVKtwgH/EE7U+XTHcoFCClJ4LR349KanzjX9xKwRcNg=
git.milar.in/milarin/channel v0.0.7/go.mod h1:We83LTI8S7u7II3pD+A2ChCDWJfCkcBUCUqii9HjTtM=
git.milar.in/milarin/gmath v0.0.3 h1:ii6rKNItS55O/wtIFhD1cTN2BMwDZjTBmiOocKURvxM=
git.milar.in/milarin/gmath v0.0.3/go.mod h1:HDLftG5RLpiNGKiIWh+O2G1PYkNzyLDADO8Cd/1abiE=

15
reduce.go Normal file
View File

@ -0,0 +1,15 @@
package slices
import "git.milar.in/milarin/gmath"
func Reduce[T, R any](slice []T, reducer func(current R, v T) R) R {
res := new(R)
Each(slice, func(v T) {
*res = reducer(*res, v)
})
return *res
}
func SumReducer[N gmath.Number](a, b N) N {
return a + b
}

11
reduce_test.go Normal file
View File

@ -0,0 +1,11 @@
package slices
import (
"fmt"
"testing"
)
func TestReduce(t *testing.T) {
s := Of(1, 2, 3)
fmt.Println(Reduce(s, SumReducer[int]))
}