-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from oze4/add-splice
Add Splice function
- Loading branch information
Showing
3 changed files
with
270 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package jslice | ||
|
||
// Splice changes the contents of a slice by removing or replacing existing elements, | ||
// and/or adding new elements. | ||
func Splice[T any](s *[]T, start uint, deleteCount uint, replacementItems ...T) { | ||
if deleteCount == 0 && len(replacementItems) == 0 { | ||
return //*s | ||
} | ||
|
||
// If start >= len(*s) no elements will be deleted, but the method will behave as | ||
// an adding function. | ||
if start >= uint(len(*s)) { | ||
if len(replacementItems) == 0 { | ||
return //*s | ||
} | ||
*s = append(*s, replacementItems...) | ||
return //*s | ||
} | ||
|
||
// If the "end" (start+deleteCount) is greater than the length of the slice, limit | ||
// the delete count to the length of the slice - start. Otherwise we get index out | ||
// of bounds error. | ||
if start + deleteCount >= uint(len(*s)) { | ||
deleteCount = uint(len(*s)) - start | ||
} | ||
|
||
*s = append((*s)[0:start], append(replacementItems, (*s)[start+deleteCount:]...)...) | ||
return //*s | ||
} |