diff --git a/README.md b/README.md index 0f09c7bc..72e1c098 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ Supported helpers for slices: - [Compact](#compact) - [IsSorted](#issorted) - [IsSortedByKey](#issortedbykey) +- [Splice](#Splice) Supported helpers for maps: @@ -980,6 +981,17 @@ slice := lo.IsSortedByKey([]string{"a", "bb", "ccc"}, func(s string) int { [[play](https://go.dev/play/p/wiG6XyBBu49)] +### Splice + +Splice multiple elements at index i. + +```go +result := lo.Splice([]string{"a", "d"}, 1, "b", "c") +// []string{"a", "b", "c", "d"} +``` + +[[play](https://go.dev/play/p/8gXdkTovsIC)] + ### Keys Creates an array of the map keys. diff --git a/slice.go b/slice.go index 7ef820ad..f2990cdf 100644 --- a/slice.go +++ b/slice.go @@ -625,3 +625,15 @@ func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(i return true } + +// Play: https://go.dev/play/p/G5_GhkeSUBA +func Splice[T any](collection []T, i int, elements ...T) []T { + if i < 0 || i > len(collection) { + panic("index out of bounds") + } + if len(elements) == 0 { + return collection + } + + return append(append(collection[:i], elements...), collection[i:]...) +} diff --git a/slice_test.go b/slice_test.go index e7e717fd..23b63947 100644 --- a/slice_test.go +++ b/slice_test.go @@ -801,3 +801,16 @@ func TestIsSortedByKey(t *testing.T) { return ret })) } + +func TestInsertSlice(t *testing.T) { + t.Parallel() + is := assert.New(t) + + inserts := Splice([]string{"a", "d"}, 1, "b", "c") + is.Equal(inserts, []string{"a", "b", "c", "d"}) + is.True(len(inserts) == 4 && inserts[1] == "b" && inserts[2] == "c") + + inserti := Splice([]int{1, 4}, 1, 2, 3) + is.Equal(inserti, []int{1, 2, 3, 4}) + is.True(len(inserti) == 4 && inserti[1] == 2 && inserti[2] == 3) +}