splice

package module
v2.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2022 License: MIT Imports: 0 Imported by: 0

README

Splice

Package splice is an generics implementation of JavaScript's array.splice function for []T where T is constrained as any.

Example

import "github.com/zzwx/splice/v2"

var months = []string{"Jan", "March", "April", "June"}
splice.Splice(&months, 1, 0, "Feb") // inserts at index 1
fmt.Println(months)
deleted := splice.Splice(&months, 4, 1, "May") // replaces 1 element at index 4
fmt.Println(months)
fmt.Println(deleted)
// Output:
// [Jan Feb March April June]
// [Jan Feb March April May]
// [June]

Documentation

Overview

Package splice is an implementation of JavaScript's array.splice function for []T.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Splice

func Splice[T any](source *[]T, start int, delete int, item ...T) (removed []T)

Splice modifies the source slice by deleting delete amount of items starting with index and replacing them with optional item(s). It returns all the elements that have been removed, nil for zero removed items.

Splice emulates JavaScript's array.splice function for type T

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

start: The index at which to start changing the slice.

If greater than the length of the slice, start will be set to the length of the slice. If negative, it will begin that many elements from the end of the slice.

delete:

An integer indicating the number of elements in the slice to remove from start. It can't be optional in Go, so 0 will act as its absence.

item(s):

The elements to add to the slice, beginning from start. If you do not specify any elements, splice() will only remove elements from the slice.

Differences from the JavaScript version:

* Only item(s) arguments may be omitted. The one integer argument call that only trims the source from start to the end of the source can be emulated using Splice(source, index, len(source)).

* No support for undefined elements or indices.

Example
var months = []string{"Jan", "March", "April", "June"}
Splice(&months, 1, 0, "Feb") // inserts at index 1
fmt.Println(months)
deleted := Splice(&months, 4, 1, "May") // replaces 1 element at index 4
fmt.Println(months)
fmt.Println(deleted)
Output:
[Jan Feb March April June]
[Jan Feb March April May]
[June]

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL