diff --git a/example_test.go b/example_test.go index 2fdd402..b34f779 100644 --- a/example_test.go +++ b/example_test.go @@ -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") @@ -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"}) @@ -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 diff --git a/slice.go b/slice.go index f1581d2..ef2c3d0 100644 --- a/slice.go +++ b/slice.go @@ -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 } @@ -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 } @@ -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 } @@ -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 @@ -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 +}