Skip to content

Commit

Permalink
adding slices.Insert
Browse files Browse the repository at this point in the history
  • Loading branch information
zostay committed Aug 13, 2023
1 parent 9deb23a commit 3f18ee2
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
WIP TBD

* Adding slices.Insert

v0.5.0 2023-07-25

* Adding fs.CreateFS, fs.WriteFileFS, fs.ReaderFS, fs.ReaderWriterFS, and fs.WriterFS
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ off-by-one errors, so the following ops are provided:

* `FromRange(a, z, delta)`
* `Delete(slice, index)`
* `DeleteValue(slice, value)`
* `DeleteAllValues(slice, value)`
* `Insert(slice, index, value)`
* `Push(slice, value)`
* `Pop(slice)`
* `Shift(slice)`
Expand Down
14 changes: 14 additions & 0 deletions slices/manipulate.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package slices

import "github.com/zostay/go-std/generic"

// Delete will remove the data at index i from the given slice. This works by
// copying the data after it back and then shortening the slice by one element.
func Delete[T any](slice []T, i int) []T {
Expand Down Expand Up @@ -33,6 +35,18 @@ func DeleteAllValues[T comparable](slice []T, s T) []T {
return slice
}

// Insert will add the data at index i into the given slice and shift the rest
// of the data up one index.
func Insert[T any](slice []T, i int, data T) []T {
if i == len(slice) {
return append(slice, data)
}
slice = append(slice, generic.Zero[T]())
copy(slice[i+1:], slice[i:])
slice[i] = data
return slice
}

// Push will add the given values to the end of the slice and return the newly
// transformed slice. The slice must be allocated or this function will panic.
func Push[T any](slice []T, v ...T) []T {
Expand Down
18 changes: 18 additions & 0 deletions slices/manipulate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,24 @@ func TestDeleteAllValues(t *testing.T) {
})
}

func TestInsert(t *testing.T) {
s := []int{1, 2, 3}

s = slices.Insert(s, 0, 4)
s = slices.Insert(s, 2, 5)
s = slices.Insert(s, 5, 6)

assert.Equal(t, []int{4, 1, 5, 2, 3, 6}, s)

assert.Panics(t, func() {
s = slices.Insert(s, -1, 0)
})

assert.Panics(t, func() {
s = slices.Insert(s, 8, 7)
})
}

func TestPop(t *testing.T) {
s := []int{1, 2, 3}

Expand Down

0 comments on commit 3f18ee2

Please sign in to comment.