From a87faf5453128d0848d35223869c01075aa4c694 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Sun, 27 Nov 2022 21:43:38 +0800 Subject: [PATCH] feat: add Repeate function for slice --- slice/slice.go | 9 +++++++++ slice/slice_test.go | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index 0adfcbf..cf3e948 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -417,6 +417,15 @@ func ReplaceAll[T comparable](slice []T, old T, new T) []T { return Replace(slice, old, new, -1) } +// Repeat creates a slice with length n whose elements are param `item`. +func Repeat[T any](item T, n int) []T { + result := make([]T, n) + for i := range result { + result[i] = item + } + return result +} + // InterfaceSlice convert param to slice of interface. func InterfaceSlice(slice any) []any { sv := sliceValue(slice) diff --git a/slice/slice_test.go b/slice/slice_test.go index 5414eb8..65b6359 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -684,3 +684,11 @@ func TestKeyBy(t *testing.T) { assert.Equal(result, map[int]string{1: "a", 2: "ab", 3: "abc"}) } + +func TestRepeat(t *testing.T) { + assert := internal.NewAssert(t, "TestRepeat") + + result := Repeat("a", 6) + + assert.Equal(result, []string{"a", "a", "a", "a", "a", "a"}) +}