Skip to content

Commit 3f18ee2

Browse files
committed
adding slices.Insert
1 parent 9deb23a commit 3f18ee2

File tree

4 files changed

+39
-0
lines changed

4 files changed

+39
-0
lines changed

Changes.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
WIP TBD
2+
3+
* Adding slices.Insert
4+
15
v0.5.0 2023-07-25
26

37
* Adding fs.CreateFS, fs.WriteFileFS, fs.ReaderFS, fs.ReaderWriterFS, and fs.WriterFS

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ off-by-one errors, so the following ops are provided:
6161

6262
* `FromRange(a, z, delta)`
6363
* `Delete(slice, index)`
64+
* `DeleteValue(slice, value)`
65+
* `DeleteAllValues(slice, value)`
66+
* `Insert(slice, index, value)`
6467
* `Push(slice, value)`
6568
* `Pop(slice)`
6669
* `Shift(slice)`

slices/manipulate.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package slices
22

3+
import "github.com/zostay/go-std/generic"
4+
35
// Delete will remove the data at index i from the given slice. This works by
46
// copying the data after it back and then shortening the slice by one element.
57
func Delete[T any](slice []T, i int) []T {
@@ -33,6 +35,18 @@ func DeleteAllValues[T comparable](slice []T, s T) []T {
3335
return slice
3436
}
3537

38+
// Insert will add the data at index i into the given slice and shift the rest
39+
// of the data up one index.
40+
func Insert[T any](slice []T, i int, data T) []T {
41+
if i == len(slice) {
42+
return append(slice, data)
43+
}
44+
slice = append(slice, generic.Zero[T]())
45+
copy(slice[i+1:], slice[i:])
46+
slice[i] = data
47+
return slice
48+
}
49+
3650
// Push will add the given values to the end of the slice and return the newly
3751
// transformed slice. The slice must be allocated or this function will panic.
3852
func Push[T any](slice []T, v ...T) []T {

slices/manipulate_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,24 @@ func TestDeleteAllValues(t *testing.T) {
102102
})
103103
}
104104

105+
func TestInsert(t *testing.T) {
106+
s := []int{1, 2, 3}
107+
108+
s = slices.Insert(s, 0, 4)
109+
s = slices.Insert(s, 2, 5)
110+
s = slices.Insert(s, 5, 6)
111+
112+
assert.Equal(t, []int{4, 1, 5, 2, 3, 6}, s)
113+
114+
assert.Panics(t, func() {
115+
s = slices.Insert(s, -1, 0)
116+
})
117+
118+
assert.Panics(t, func() {
119+
s = slices.Insert(s, 8, 7)
120+
})
121+
}
122+
105123
func TestPop(t *testing.T) {
106124
s := []int{1, 2, 3}
107125

0 commit comments

Comments
 (0)