Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add slice Splice an element or multiple elements at index i. #371

Merged
merged 6 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ Supported helpers for slices:
- [Compact](#compact)
- [IsSorted](#issorted)
- [IsSortedByKey](#issortedbykey)
- [Splice](#Splice)

Supported helpers for maps:

Expand Down Expand Up @@ -980,6 +981,17 @@ slice := lo.IsSortedByKey([]string{"a", "bb", "ccc"}, func(s string) int {

[[play](https://go.dev/play/p/wiG6XyBBu49)]

### Splice

Insert 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/G5_GhkeSUBA)]

### Keys

Creates an array of the map keys.
Expand Down
12 changes: 12 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:]...)
}
13 changes: 13 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -801,3 +801,16 @@ func TestIsSortedByKey(t *testing.T) {
return ret
}))
}

func TestInsertSlice(t *testing.T) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
func TestInsertSlice(t *testing.T) {
func TestSplice(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)
}
Loading