From c87f3f88b7059e4a48052ef81efe7c5a5a27dcc6 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Wed, 10 Aug 2022 16:57:00 +0200 Subject: [PATCH 1/2] add flatmap Signed-off-by: Ruidy --- docs/content/collections/flatmap.md | 23 +++++++++++++++++++++++ flatmap.go | 11 +++++++++++ flatmap_test.go | 16 ++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 docs/content/collections/flatmap.md create mode 100644 flatmap.go create mode 100644 flatmap_test.go diff --git a/docs/content/collections/flatmap.md b/docs/content/collections/flatmap.md new file mode 100644 index 0000000..80033fa --- /dev/null +++ b/docs/content/collections/flatmap.md @@ -0,0 +1,23 @@ +--- +title: "Flatmap" +date: 2022-08-10T16:49:56+02:00 +draft: false +--- + +Flatmap flattens the input slice element into the new slice. FlatMap maps every element with the help of a mapper function, then flattens the input slice element into the new slice. + +```go +package main + +import ( + "fmt" + u "github.com/rjNemo/underscore" +) + +func main() { + nums := []int{1, 2, 3, 4} + mapper := func(n int) []int { return []int{(n - 1) * n, (n) * n} } + res := u.Flatmap(nums, mapper) + fmt.Println(res) // {0, 1, 2, 4, 6, 9, 12, 16} +} +``` diff --git a/flatmap.go b/flatmap.go new file mode 100644 index 0000000..1ce9c80 --- /dev/null +++ b/flatmap.go @@ -0,0 +1,11 @@ +package underscore + +// Flatmap flatten the input slice element into the new slice. FlatMap maps every element with the help of a mapper function, then flattens the input slice element into the new slice. +func Flatmap[T any](values []T, mapper func(n T) []T) []T { + res := make([]T, 0) + for _, v := range values { + vs := mapper(v) + res = append(res, vs...) + } + return res +} diff --git a/flatmap_test.go b/flatmap_test.go new file mode 100644 index 0000000..29fdb10 --- /dev/null +++ b/flatmap_test.go @@ -0,0 +1,16 @@ +package underscore_test + +import ( + "testing" + + u "github.com/rjNemo/underscore" + "github.com/stretchr/testify/assert" +) + +func TestFlatmap(t *testing.T) { + nums := []int{1, 2, 3, 4} + transform := func(n int) []int { return []int{(n - 1) * n, (n) * n} } + want := []int{0, 1, 2, 4, 6, 9, 12, 16} + + assert.Equal(t, want, u.Flatmap(nums, transform)) +} From dafb519fbd2b6d489f41e979de9bc16e8805498e Mon Sep 17 00:00:00 2001 From: Ruidy Date: Wed, 10 Aug 2022 16:58:34 +0200 Subject: [PATCH 2/2] add to readme Signed-off-by: Ruidy --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7660558..19325e9 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,7 @@ make test - `Contains` (only numerics values at the moment) - `Each` - `Filter` +- `Flatmap` - `Find` - `Map` - `Max`