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
22 changes: 22 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,28 @@ func ExampleSlice_Insert() {
// [one two three four]
}

func ExampleSlice_Replace() {
s := slice.FromRaw([]string{"one", "two", "two", "two", "two"})
s.Replace(2, "three", "four", "five")
fmt.Println(s)

// Output:
// [one two three four five]
}

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

// cannot replace 3 elements starting from index 2
// the given slice does not have enough elements
fmt.Println(s.Replace(2, "three", "four", "five"))
fmt.Println(s)

// Output:
// false
// [one two two two]
}

func ExampleSlice_Insert_false() {
s := slice.FromRaw[string](nil)
fmt.Println(s.Insert(1, "one")) // the highest possible index to insert == len(s)
Expand Down
16 changes: 16 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,22 @@ func (s *Slice[T]) Insert(index int, v ...T) (ok bool) {
return true
}

// Replace replaces s[index:index+len(v)] with v.
// It does not succeed when the given slice does not have enough elements to be replaced.
//
// s := slice.FromRaw([]string{"one", "two", "two", "two", "two"})
// 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) {
if index < 0 || index+len(v) > len(*s) {
return false
}

copy((*s)[index:index+len(v)], v)

return true
}

// Clone returns a new slice with the same length and copies to it all the elements from the existing slice.
func (s *Slice[T]) Clone() Slice[T] {
if *s == nil {
Expand Down
Loading