From 82f7401368ce00d8f6657cbc6a1182801ba59ec6 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Thu, 14 Jul 2022 11:53:16 +0800 Subject: [PATCH] feat: add Flatten function --- slice/slice.go | 27 +++++++++++++++++++++++++++ slice/slice_test.go | 8 ++++++++ 2 files changed, 35 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index 094dd1f..30bcefd 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -355,6 +355,33 @@ func FindLast[T any](slice []T, predicate func(index int, item T) bool) (*T, boo return &slice[index], true } +// Flatten flattens slice with one level +func Flatten(slice any) any { + sv := sliceValue(slice) + + var res reflect.Value + if sv.Type().Elem().Kind() == reflect.Interface { + res = reflect.MakeSlice(reflect.TypeOf([]interface{}{}), 0, sv.Len()) + } else if sv.Type().Elem().Kind() == reflect.Slice { + res = reflect.MakeSlice(sv.Type().Elem(), 0, sv.Len()) + } else { + return res + } + + for i := 0; i < sv.Len(); i++ { + item := reflect.ValueOf(sv.Index(i).Interface()) + if item.Kind() == reflect.Slice { + for j := 0; j < item.Len(); j++ { + res = reflect.Append(res, item.Index(j)) + } + } else { + res = reflect.Append(res, item) + } + } + + return res.Interface() +} + // FlattenDeep flattens slice recursive func FlattenDeep(slice any) any { sv := sliceValue(slice) diff --git a/slice/slice_test.go b/slice/slice_test.go index 60eed77..543c60f 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -236,6 +236,14 @@ func TestFindFoundNothing(t *testing.T) { assert.Equal(false, ok) } +func TestFlatten(t *testing.T) { + input := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + expected := [][]string{{"a", "b"}, {"c", "d"}} + + assert := internal.NewAssert(t, "TestFlattenDeep") + assert.Equal(expected, Flatten(input)) +} + func TestFlattenDeep(t *testing.T) { input := [][][]string{{{"a", "b"}}, {{"c", "d"}}} expected := []string{"a", "b", "c", "d"}