From f3801bcd8f2a88144aca59465cbaaebb9bf79f0a Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 24 Feb 2023 11:14:59 +0800 Subject: [PATCH] feat: add FlatMap --- slice/slice.go | 12 ++++++++++++ slice/slice_example_test.go | 14 ++++++++++++++ slice/slice_test.go | 13 +++++++++++++ 3 files changed, 39 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index bf23c5d..6ea2f54 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -438,6 +438,18 @@ func FilterMap[T any, U any](slice []T, iteratee func(index int, item T) (U, boo return result } +// FlatMap manipulates a slice and transforms and flattens it to a slice of another type. +// Play: todo +func FlatMap[T any, U any](slice []T, iteratee func(index int, item T) []U) []U { + result := make([]U, 0, len(slice)) + + for i, v := range slice { + result = append(result, iteratee(i, v)...) + } + + return result +} + // Reduce creates an slice of values by running each element of slice thru iteratee function. // Play: https://go.dev/play/p/_RfXJJWIsIm func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T { diff --git a/slice/slice_example_test.go b/slice/slice_example_test.go index 3f4807f..045e846 100644 --- a/slice/slice_example_test.go +++ b/slice/slice_example_test.go @@ -386,6 +386,20 @@ func ExampleFilterMap() { // []string{"2", "4"} } +func ExampleFlatMap() { + nums := []int{1, 2, 3, 4} + + result := FlatMap(nums, func(i int, num int) []string { + s := "hi-" + strconv.FormatInt(int64(num), 10) + return []string{s} + }) + + fmt.Printf("%#v", result) + + // Output: + // []string{"hi-1", "hi-2", "hi-3", "hi-4"} +} + func ExampleReduce() { nums := []int{1, 2, 3} diff --git a/slice/slice_test.go b/slice/slice_test.go index 563a582..99ee415 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -333,6 +333,19 @@ func TestFilterMap(t *testing.T) { assert.Equal([]string{"2", "4"}, result) } +func TestFlatMap(t *testing.T) { + assert := internal.NewAssert(t, "TestFlatMap") + + nums := []int{1, 2, 3, 4} + + result := FlatMap(nums, func(i int, num int) []string { + s := "hi-" + strconv.FormatInt(int64(num), 10) + return []string{s} + }) + + assert.Equal([]string{"hi-1", "hi-2", "hi-3", "hi-4"}, result) +} + func TestReduce(t *testing.T) { cases := [][]int{ {},