Skip to content

Commit

Permalink
add Remove and its tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkRosemaker committed Jul 13, 2022
1 parent c9f230d commit 95bf3bc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
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

0 comments on commit 95bf3bc

Please sign in to comment.