Skip to content
Merged
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
20 changes: 19 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ func ExampleSlice_Delete() {
// [two five]
}

func ExampleSlice_Delete_last() {
s := slice.FromRaw([]int{1, 2, 3, 4, 5})
s.Delete(-1 /* index */, 1 /* length */)

fmt.Println(s)

// Output: [1 2 3 4]
}

func ExampleSlice_Insert() {
s := slice.FromRaw([]string{"one", "four"})
s.Insert(1, "two", "three")
Expand All @@ -167,6 +176,15 @@ func ExampleSlice_Replace() {
// [one two three four five]
}

func ExampleSlice_Replace_last() {
s := slice.FromRaw([]int{1, 2, 3, 4, 4})
s.Replace(-1, 5)
fmt.Println(s)

// Output:
// [1 2 3 4 5]
}

func ExampleSlice_Replace_false() {
s := slice.FromRaw([]string{"one", "two", "two", "two"})

Expand All @@ -185,7 +203,7 @@ func ExampleSlice_Insert_false() {
fmt.Println(s.Insert(1, "one")) // the highest possible index to insert == len(s)

s = slice.FromRaw([]string{"zero", "one", "two"})
fmt.Println(s.Insert(-1, "minus one")) // index MUST be >= 0
fmt.Println(s.Insert(-100, "minus one")) // invalid index

// Output:
// false
Expand Down
18 changes: 15 additions & 3 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ func (s *Slice[T]) DeleteOne(index int) (ok bool) {
// s.Delete(1, 3)
// fmt.Println(s) [1 5]
func (s *Slice[T]) Delete(index int, length int) (ok bool) {
index = s.solveIndex(index)

if index < 0 || *s == nil || index+length > len(*s) {
return false
}
Expand All @@ -120,6 +122,8 @@ func (s *Slice[T]) Delete(index int, length int) (ok bool) {
// s.Insert(1 "two", "three")
// fmt.Println(s) // ["one", "two", "three", "four"]
func (s *Slice[T]) Insert(index int, v ...T) (ok bool) {
index = s.solveIndex(index)

if index < 0 || index > len(*s) {
return false
}
Expand All @@ -144,6 +148,8 @@ func (s *Slice[T]) Insert(index int, v ...T) (ok bool) {
// s.Replace(2, "three", "four", "five")
// fmt.Println(s) // [one two three four five]
func (s *Slice[T]) Replace(index int, v ...T) (ok bool) {
index = s.solveIndex(index)

if index < 0 || index+len(v) > len(*s) {
return false
}
Expand Down Expand Up @@ -201,9 +207,7 @@ func (s *Slice[T]) Filter(keep func(index int, val T) bool) {
// val, ok := x.Get(-1)
// fmt.Println(val) // 5
func (s *Slice[T]) Get(index int) (_ T, ok bool) {
if index < 0 {
index += len(*s)
}
index = s.solveIndex(index)

if index < 0 || index >= len(*s) {
var r T
Expand Down Expand Up @@ -240,3 +244,11 @@ func (s *Slice[T]) Shuffle(randIntN func(n int) int) {
(*s)[i], (*s)[j] = (*s)[j], (*s)[i]
}
}

func (s *Slice[T]) solveIndex(i int) int {
if i < 0 {
i += len(*s)
}

return i
}
Loading