fix: panic when passing -1 to Drop (#688)

This commit is contained in:
Nathan Baulch
2025-09-25 21:11:52 +10:00
committed by GitHub
parent 508d49270f
commit 2911f93956
2 changed files with 18 additions and 0 deletions

View File

@@ -439,6 +439,10 @@ func Keyify[T comparable, Slice ~[]T](collection Slice) map[T]struct{} {
// Drop drops n elements from the beginning of a slice.
// Play: https://go.dev/play/p/JswS7vXRJP2
func Drop[T any, Slice ~[]T](collection Slice, n int) Slice {
if n < 0 {
panic("lo.Drop: n must not be negative")
}
if len(collection) <= n {
return make(Slice, 0)
}
@@ -451,6 +455,10 @@ func Drop[T any, Slice ~[]T](collection Slice, n int) Slice {
// DropRight drops n elements from the end of a slice.
// Play: https://go.dev/play/p/GG0nXkSJJa3
func DropRight[T any, Slice ~[]T](collection Slice, n int) Slice {
if n < 0 {
panic("lo.DropRight: n must not be negative")
}
if len(collection) <= n {
return Slice{}
}

View File

@@ -615,6 +615,7 @@ func TestDrop(t *testing.T) {
t.Parallel()
is := assert.New(t)
is.Equal([]int{0, 1, 2, 3, 4}, Drop([]int{0, 1, 2, 3, 4}, 0))
is.Equal([]int{1, 2, 3, 4}, Drop([]int{0, 1, 2, 3, 4}, 1))
is.Equal([]int{2, 3, 4}, Drop([]int{0, 1, 2, 3, 4}, 2))
is.Equal([]int{3, 4}, Drop([]int{0, 1, 2, 3, 4}, 3))
@@ -622,6 +623,10 @@ func TestDrop(t *testing.T) {
is.Empty(Drop([]int{0, 1, 2, 3, 4}, 5))
is.Empty(Drop([]int{0, 1, 2, 3, 4}, 6))
is.PanicsWithValue("lo.Drop: n must not be negative", func() {
Drop([]int{0, 1, 2, 3, 4}, -1)
})
type myStrings []string
allStrings := myStrings{"", "foo", "bar"}
nonempty := Drop(allStrings, 2)
@@ -632,6 +637,7 @@ func TestDropRight(t *testing.T) {
t.Parallel()
is := assert.New(t)
is.Equal([]int{0, 1, 2, 3, 4}, DropRight([]int{0, 1, 2, 3, 4}, 0))
is.Equal([]int{0, 1, 2, 3}, DropRight([]int{0, 1, 2, 3, 4}, 1))
is.Equal([]int{0, 1, 2}, DropRight([]int{0, 1, 2, 3, 4}, 2))
is.Equal([]int{0, 1}, DropRight([]int{0, 1, 2, 3, 4}, 3))
@@ -639,6 +645,10 @@ func TestDropRight(t *testing.T) {
is.Empty(DropRight([]int{0, 1, 2, 3, 4}, 5))
is.Empty(DropRight([]int{0, 1, 2, 3, 4}, 6))
is.PanicsWithValue("lo.DropRight: n must not be negative", func() {
DropRight([]int{0, 1, 2, 3, 4}, -1)
})
type myStrings []string
allStrings := myStrings{"", "foo", "bar"}
nonempty := DropRight(allStrings, 2)