Documentation ¶
Overview ¶
Package slices ...
Package slices is a collection of functions to operate with string slices. Some functions were adapted from the strings package to work with slices, other were ported from PHP 'array_*' function equivalents.
Example (Basic) ¶
This example shows basic usage of various functions by manipulating the slice 'slc'.
package main import ( "fmt" "strings" "github.com/srfrog/slices" ) func main() { str := `Don't communicate by sharing memory - share memory by communicating` // Split string by spaces into a slice. slc := strings.Split(str, " ") // Count the number of "memory" strings in slc. memories := slices.Count(slc, "memory") fmt.Println("Memories:", memories) // Split slice into two parts. parts := slices.Split(slc, "-") fmt.Println("Split:", parts, len(parts)) // Compare second parts slice with original slc. diff := slices.Diff(slc, parts[1]) fmt.Println("Diff:", diff) // Chunk the slice chunks := slices.Chunk(parts[0], 1) fmt.Println("Chunk:", chunks) // Merge the parts merge := slices.Merge(chunks...) fmt.Println("Merge:", merge) }
Output: Memories: 2 Split: [[Don't communicate by sharing memory] [share memory by communicating]] 2 Diff: [Don't communicate sharing -] Chunk: [[Don't] [communicate] [by] [sharing] [memory]] Merge: [Don't communicate by sharing memory]
Index ¶
- Constants
- func Chunk(a []string, size int) [][]string
- func Compare(a, b []string) int
- func CompareFunc(a, b []string, f func(string, string) bool) int
- func Contains(a []string, s string) bool
- func ContainsAny(a, b []string) bool
- func ContainsPrefix(a []string, prefix string) bool
- func ContainsSuffix(a []string, suffix string) bool
- func Count(a []string, s string) int
- func Diff(a, b []string) []string
- func DiffFunc(a, b []string, f func([]string, string) bool) []string
- func Equal(a, b []string) bool
- func EqualFold(a, b []string) bool
- func Fill(n int, s string) []string
- func Filter(a []string, s string) []string
- func FilterFunc(a []string, f ValueFunc) []string
- func FilterPrefix(a []string, prefix string) []string
- func FilterSuffix(a []string, suffix string) []string
- func Index(a []string, s string) int
- func IndexAny(a, b []string) int
- func IndexFunc(a []string, f ValueFunc) int
- func InsertAt(a []string, idx int, values ...string) []string
- func Intersect(a, b []string) []string
- func LastIndex(a []string, s string) int
- func LastIndexAny(a, b []string) int
- func LastIndexFunc(a []string, f ValueFunc) int
- func LastSearch(a []string, substr string) int
- func Map(mapping func(string) string, a []string) []string
- func Merge(aa ...[]string) []string
- func Pop(a *[]string) string
- func Push(a *[]string, values ...string) int
- func Rand(a []string, n int) []string
- func RandFunc(a []string, n int, f func(int) int) []string
- func Reduce(a []string, f func(string, int, string) string) string
- func Repeat(s string, count int) []string
- func RepeatFunc(f func() string, count int) []string
- func Replace(a []string, old, new string, n int) []string
- func ReplaceAll(a []string, old, new string) []string
- func Reverse(a []string) []string
- func Search(a []string, substr string) int
- func Shift(a *[]string) string
- func Shuffle(a []string) []string
- func Slice(a []string, offset, length int) []string
- func Splice(a []string, offset, length int, b ...string) []string
- func Split(a []string, sep string) [][]string
- func SplitN(a []string, sep string, n int) [][]string
- func Trim(a []string, s string) []string
- func TrimFunc(a []string, f ValueFunc) []string
- func TrimPrefix(a []string, prefix string) []string
- func TrimSuffix(a []string, suffix string) []string
- func Unique(a []string) []string
- func Unshift(a *[]string, s ...string) int
- func Walk(a []string, f func(idx int, val string))
- type ValueFunc
Examples ¶
Constants ¶
const Version = "1.0.0"
Version is the version of this package.
Variables ¶
This section is empty.
Functions ¶
func Chunk ¶
Chunk will divide a slice into subslices with size elements into a new 2d slice. The last chunk may contain less than size elements. If size less than 1, Chunk returns nil.
Example ¶
package main import ( "fmt" "strings" "github.com/srfrog/slices" ) func main() { // Top 3 programming languages data := `1,C,16%,2,Java,13%,3,Python,11%` slc := strings.Split(data, ",") // Split into chunks of 3. chunks := slices.Chunk(slc, 3) fmt.Println("Chunks:", chunks) // Replace C with Go once. chunks[0] = slices.Replace(chunks[0], "C", "Go", 1) fmt.Println("Replace:", chunks) }
Output: Chunks: [[1 C 16%] [2 Java 13%] [3 Python 11%]] Replace: [[1 Go 16%] [2 Java 13%] [3 Python 11%]]
func Compare ¶
Compare returns an integer comparing two slices lexicographically. The result will be 0 if a==b, or that a has all values of b. The result will be -1 if a < b, or a is shorter than b. The result will be +1 if a > b, or a is longer than b. A nil argument is equivalent to an empty slice.
func CompareFunc ¶
CompareFunc returns an integer comparing two slices with func f.
func ContainsAny ¶
ContainsAny returns true if any value in b is in a, false otherwise
func ContainsPrefix ¶
ContainsPrefix returns true if any element in a has prefix, false otherwise
func ContainsSuffix ¶
ContainsSuffix returns true if any element in a has suffix, false otherwise
func DiffFunc ¶ added in v1.0.1
DiffFunc compares the elements of b with those of b using f func. It returns a slice of the elements in b that are not found in a where cmp() == true.
func Equal ¶
Equal returns a boolean reporting whether a and b are the same length and contain the same values, when compared lexicographically.
func EqualFold ¶
EqualFold returns a boolean reporting whether a and b are the same length and their values are equal under Unicode case-folding.
func FilterFunc ¶
FilterFunc returns a slice with all the elements of a that match string s that satisfy f(s). If func f returns true, the value will be filtered from b.
func FilterPrefix ¶
FilterPrefix returns a slice with all the elements of a that have prefix.
func FilterSuffix ¶
FilterSuffix returns a slice with all the elements of a that have suffix.
func IndexFunc ¶
IndexFunc returns the index of the first element in a where f(s) == true, or -1 if not found.
func InsertAt ¶
InsertAt inserts the values in slice a at index idx. This func will append the values if idx doesn't fit in the slice or is negative.
func LastIndexAny ¶
LastIndexAny returns the index of the last instance of b in a, or -1 if not found
func LastIndexFunc ¶
LastIndexFunc returns the index of the last element in a where f(s) == true, or -1 if not found.
func LastSearch ¶
LastSearch returns the index of the last element containing substr in a, or -1 if not found. An empty substr matches any.
func Pop ¶
Pop removes the last element in a and returns it, shortening the slice by one. If a is empty returns empty string "". Note that this function will change the slice pointed by a.
func Push ¶
Push appends one or more values to a and returns the number of elements. Note that this function will change the slice pointed by a.
func Rand ¶
Rand returns a new slice with n number of random elements of a using rand.Intn to select the elements. Note: You may want initialize the rand seed once in your program.
rand.Seed(time.Now().UnixNano())
func RandFunc ¶ added in v1.0.1
RandFunc returns a new slice with n number of random elements of a using func f to select the elements.
Example ¶
package main import ( crand "crypto/rand" "fmt" "math/big" "strings" "github.com/srfrog/slices" ) func main() { const ( chars = `abcdefghijklmnopqrstuvwxz` charsLen = len(chars) ) getIntn := func(max int) int { n, _ := crand.Int(crand.Reader, big.NewInt(int64(max))) return int(n.Int64()) } getRandStr := func() string { var sb strings.Builder m := getIntn(charsLen) for sb.Len() < m { sb.WriteByte(chars[getIntn(charsLen)]) } return sb.String() } // Generate a slice with 10 random strings. slc := slices.RepeatFunc(getRandStr, 10) fmt.Println("RepeatFunc len():", len(slc)) // Pick 3 random elements from slc. out := slices.RandFunc(slc, 3, getIntn) fmt.Println("RandFunc len():", len(out)) fmt.Println("ContainsAny:", slices.ContainsAny(slc, out)) }
Output: RepeatFunc len(): 10 RandFunc len(): 3 ContainsAny: true
func Reduce ¶ added in v1.0.1
Reduce applies the f func to each element in a and aggregates the result in acc and returns the total of the iterations. If there is only one value in the slice, it is returned. This func panics if f func is nil, or if the slice is empty.
func RepeatFunc ¶ added in v1.0.1
RepeatFunc applies func f and returns a slice consisting of count values.
func Replace ¶
Replace returns a copy of the slice a with the first n instances of old replaced by new. If n < 0, there is no limit on the number of replacements.
func ReplaceAll ¶
ReplaceAll returns a copy of the slice a with all instances of old replaced by new.
func Search ¶
Search returns the index of the first element containing substr in a, or -1 if not found. An empty substr matches any.
func Shift ¶
Shift shifts the first element of a and returns it, shortening the slice by one. If a is empty returns empty string "". Note that this function will change the slice pointed by a.
Example ¶
package main import ( "fmt" "github.com/srfrog/slices" ) func main() { slc := []string{"Go", "nuts", "for", "Go"} slices.Shift(&slc) // returns "Go" fmt.Println("Shift:", slc) slices.Unshift(&slc, "Really") // returns 4 fmt.Println("Unshift:", slc) }
Output: Shift: [nuts for Go] Unshift: [Really nuts for Go]
func Shuffle ¶
Shuffle returns a slice with randomized order of elements in a. Note: You may want initialize the rand seed once in your program.
rand.Seed(time.Now().UnixNano())
func Slice ¶
Slice returns a subslice of the elements from the slice a as specified by the offset and length parameters.
If offset > 0 the subslice will start at that offset in the slice. If offset < 0 the subslice will start that far from the end of the slice.
If length > 0 then the subslice will have up to that many elements in it. If length == 0 then the subslice will begin from offset up to the end of the slice. If length < 0 then the subslice will stop that many elements from the end of the slice. If the slice a is shorter than the length, then only the available elements will be present.
If the offset is larger than the size of the slice, an empty slice is returned.
func Splice ¶
Splice removes a portion of the slice a and replace it with the elements of another.
If offset > 0 then the start of the removed portion is at that offset from the beginning of the slice. If offset < 0 then the start of the removed portion is at that offset from the end of the slice.
If length > 0 then that many elements will be removed. If length == 0 no elements will be removed. If length == size removes everything from offset to the end of slice. If length < 0 then the end of the removed portion will be that many elements from the end of the slice.
If b == nil then length elements are removed from a at offset. If b != nil then the elements are inserted at offset.
func Split ¶
Split divides a slice a into subslices when any element matches the string sep.
If a does not contain sep and sep is not empty, Split returns a 2d slice of length 1 whose only element is a.
If sep is empty, Split returns a 2d slice of all elements in a. If a is nil and sep is empty, Split returns an empty slice.
Split is akin to SplitN with a count of -1.
func SplitN ¶
Split divides a slice a into subslices when n elements match the string sep.
The count determines the number of subslices to return:
n > 0: at most n subslices; the last element will be the unsplit remainder. n == 0: the result is nil (zero subslices) n < 0: all subslices
For other cases, see the documentation for Split.
func TrimFunc ¶
TrimFunc returns a slice with all the elements of a that don't match string s that satisfy f(s). If func f returns true, the value will be trimmed from a.
func TrimPrefix ¶
TrimPrefix returns a slice with all the elements of a that don't have prefix.
func TrimSuffix ¶
TrimSuffix returns a slice with all the elements of a that don't have suffix.
func Unshift ¶
Unshift prepends one or more elements to *a and returns the number of elements. Note that this function will change the slice pointed by a
func Walk ¶ added in v1.0.1
Walk applies the f func to each element in a.
Example ¶
package main import ( "fmt" "strings" "github.com/srfrog/slices" ) func main() { var n int slc := []string{"Go", "go", "GO"} // Count the Go's. slices.Walk(slc, func(i int, v string) { if strings.EqualFold(v, "Go") { n++ } }) fmt.Println("Count:", n) // Convert a slice into a map. m := make(map[int]string) slices.Walk(slc, func(i int, v string) { m[i] = v }) fmt.Println("Mapize:", m) }
Output: Count: 3 Mapize: map[0:Go 1:go 2:GO]
Types ¶
type ValueFunc ¶ added in v1.0.1
ValueFunc is a value comparison func, used to compare element values in a slice.
func ValueContains ¶ added in v1.0.1
ValueContains returns true if element value v contains substr.
func ValueEquals ¶ added in v1.0.1
ValueEquals returns true if element value v equals s.
func ValueHasPrefix ¶ added in v1.0.1
ValueHasPrefix returns true if element value begins with prefix.
func ValueHasSuffix ¶ added in v1.0.1
ValueHasPrefix returns true if element value ends with suffix.