Skip to content

Commit

Permalink
change name to Splice and use leverage vaargs to write
Browse files Browse the repository at this point in the history
  • Loading branch information
wenlingang committed Jun 29, 2024
1 parent 8809c7b commit 5e79a80
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 22 deletions.
11 changes: 2 additions & 9 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,15 +593,8 @@ func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(i
return true
}

// Insert inserts an element at index i.
// Play: https://go.dev/play/p/Eu3pk6_ODVQ
func Insert[T any](collection []T, i int, element T) []T {
return append(collection[:i], append([]T{element}, collection[i:]...)...)
}

// InsertSlice inserts multiple elements at index i.
// Play: https://go.dev/play/p/8gXdkTovsIC
func InsertSlice[T any](collection []T, i int, elements []T) []T {
// 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")
}
Expand Down
15 changes: 2 additions & 13 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -760,24 +760,13 @@ func TestIsSortedByKey(t *testing.T) {
}))
}

func TestInsert(t *testing.T) {
t.Parallel()
is := assert.New(t)

inserts := Insert([]string{"a", "c", "d"}, 1, "b")
is.True(len(inserts) == 4 && inserts[1] == "b")

inserti := Insert([]int{1, 3, 4}, 1, 2)
is.True(len(inserti) == 4 && inserti[1] == 2)
}

func TestInsertSlice(t *testing.T) {
t.Parallel()
is := assert.New(t)

inserts := InsertSlice([]string{"a", "d"}, 1, []string{"b", "c"})
inserts := Splice([]string{"a", "d"}, 1, "b", "c")
is.True(len(inserts) == 4 && inserts[1] == "b" && inserts[2] == "c")

inserti := InsertSlice([]int{1, 4}, 1, []int{2, 3})
inserti := Splice([]int{1, 4}, 1, 2, 3)
is.True(len(inserti) == 4 && inserti[1] == 2 && inserti[2] == 3)
}

0 comments on commit 5e79a80

Please sign in to comment.