Skip to content

Commit

Permalink
Add slice Splice an element or multiple elements at index i.
Browse files Browse the repository at this point in the history
  • Loading branch information
wenlingang committed Jun 29, 2024
1 parent 2a74434 commit fec056c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ Supported helpers for slices:
- [Compact](#compact)
- [IsSorted](#issorted)
- [IsSortedByKey](#issortedbykey)
- [Splice](#Splice)

Supported helpers for maps:

Expand Down Expand Up @@ -923,6 +924,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.
Expand Down
12 changes: 12 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,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:]...)
}
17 changes: 15 additions & 2 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func TestAssociate(t *testing.T) {

func TestSliceToMap(t *testing.T) {
t.Parallel()

type foo struct {
baz string
bar int
Expand Down Expand Up @@ -626,7 +626,7 @@ func TestSlice(t *testing.T) {
out16 := Slice(in, -10, 1)
out17 := Slice(in, -1, 3)
out18 := Slice(in, -10, 7)

is.Equal([]int{}, out1)
is.Equal([]int{0}, out2)
is.Equal([]int{0, 1, 2, 3, 4}, out3)
Expand Down Expand Up @@ -759,3 +759,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)
}

0 comments on commit fec056c

Please sign in to comment.