diff --git a/slice.go b/slice.go index 2be7dd9..d96e3d8 100644 --- a/slice.go +++ b/slice.go @@ -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{} } diff --git a/slice_test.go b/slice_test.go index f84ea9d..4d00831 100644 --- a/slice_test.go +++ b/slice_test.go @@ -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)