From ab6e6684f81776f199f3f9706864a6e7a925e661 Mon Sep 17 00:00:00 2001 From: milarin Date: Thu, 9 Mar 2023 14:34:44 +0100 Subject: [PATCH] added Reduce method --- go.mod | 4 +++- go.sum | 4 ++-- reduce.go | 15 +++++++++++++++ reduce_test.go | 11 +++++++++++ 4 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 reduce.go create mode 100644 reduce_test.go diff --git a/go.mod b/go.mod index 53fb616..f1fa267 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.milar.in/milarin/slices -go 1.19 \ No newline at end of file +go 1.19 + +require git.milar.in/milarin/gmath v0.0.3 diff --git a/go.sum b/go.sum index e592c3c..4e47344 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/reduce.go b/reduce.go new file mode 100644 index 0000000..cd56b32 --- /dev/null +++ b/reduce.go @@ -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 +} diff --git a/reduce_test.go b/reduce_test.go new file mode 100644 index 0000000..14df6d4 --- /dev/null +++ b/reduce_test.go @@ -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])) +}