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 Remove to remove an item from a slice #180

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,22 @@ func KeyBy[K comparable, V any](collection []V, iteratee func(V) K) map[K]V {
return result
}

// Remove removes an element from the slice or array.
func Remove[T any](collection []T, i int) []T {
end := len(collection) - 1

if i > end {
panic("Index must exist in slice")
}

copy(collection[i:], collection[i+1:])

var zero T
collection[end] = zero

return collection[:end]
}

// Drop drops n elements from the beginning of a slice or array.
func Drop[T any](collection []T, n int) []T {
if len(collection) <= n {
Expand Down
13 changes: 13 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,19 @@ func TestKeyBy(t *testing.T) {
is.Equal(result1, map[int]string{1: "a", 2: "aa", 3: "aaa"})
}

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

is.Equal([]int{1, 2, 3, 4}, Remove([]int{0, 1, 2, 3, 4}, 0))
is.Equal([]int{0, 2, 3, 4}, Remove([]int{0, 1, 2, 3, 4}, 1))
is.Equal([]int{0, 1, 3, 4}, Remove([]int{0, 1, 2, 3, 4}, 2))
is.Equal([]int{0, 1, 2, 4}, Remove([]int{0, 1, 2, 3, 4}, 3))
is.Equal([]int{0, 1, 2, 3}, Remove([]int{0, 1, 2, 3, 4}, 4))

is.PanicsWithValue("Index must exist in slice",
func() { is.Equal([]int{}, Remove([]int{0, 1, 2, 3, 4}, 5)) })
}

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

Expand Down