diff --git a/Changes.md b/Changes.md index 50e155d..f3a84cb 100644 --- a/Changes.md +++ b/Changes.md @@ -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 diff --git a/README.md b/README.md index 78e8eda..e403e6d 100644 --- a/README.md +++ b/README.md @@ -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)` diff --git a/slices/manipulate.go b/slices/manipulate.go index 85010df..25de026 100644 --- a/slices/manipulate.go +++ b/slices/manipulate.go @@ -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 { @@ -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 { diff --git a/slices/manipulate_test.go b/slices/manipulate_test.go index 441330c..71d91fb 100644 --- a/slices/manipulate_test.go +++ b/slices/manipulate_test.go @@ -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}