slices

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2020 License: MIT Imports: 2 Imported by: 1

README

Slices

PkgGoDev Go Report Card codecov Build Status

Functions that operate on slices. Similar to functions from package strings or package bytes that have been adapted to work with slices.

Features

  • Using a thin layer of idiomatic Go; correctness over performance.
  • Provide most basic slice operations: index, trim, filter, map
  • Some PHP favorites like: pop, push, shift, unshift, shuffle, etc...
  • Non-destructive returns (won't alter original slice), except for explicit tasks.

Quick Start

Install using "go get":

go get github.com/srfrog/slices

Then import from your source:

import "github.com/srfrog/slices"

View example_test.go for examples of basic usage and features.

Documentation

The full code documentation is located at GoDoc:

http://godoc.org/github.com/srfrog/slices

Usage

This is a en example showing basic usage.

package main

import(
   "fmt"

   "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)
}

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

Examples

Constants

View Source
const Version = "1.0.0"

Version is the version of this package.

Variables

This section is empty.

Functions

func Chunk

func Chunk(a []string, size int) [][]string

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

func Compare(a, b []string) int

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

func CompareFunc(a, b []string, f func(string, string) bool) int

CompareFunc returns an integer comparing two slices with func f.

func Contains

func Contains(a []string, s string) bool

Contains returns true if s is in a, false otherwise

func ContainsAny

func ContainsAny(a, b []string) bool

ContainsAny returns true if any value in b is in a, false otherwise

func ContainsPrefix

func ContainsPrefix(a []string, prefix string) bool

ContainsPrefix returns true if any element in a has prefix, false otherwise

func ContainsSuffix

func ContainsSuffix(a []string, suffix string) bool

ContainsSuffix returns true if any element in a has suffix, false otherwise

func Count

func Count(a []string, s string) int

Count returns the number of occurrences of s in a.

func Diff

func Diff(a, b []string) []string

Diff returns a slice with all the elements of b that are not found in a.

func DiffFunc added in v1.0.1

func DiffFunc(a, b []string, f func([]string, string) bool) []string

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

func Equal(a, b []string) bool

Equal returns a boolean reporting whether a and b are the same length and contain the same values, when compared lexicographically.

func EqualFold

func EqualFold(a, b []string) bool

EqualFold returns a boolean reporting whether a and b are the same length and their values are equal under Unicode case-folding.

func Fill

func Fill(n int, s string) []string

Fill is an alias of Repeat.

func Filter

func Filter(a []string, s string) []string

Filter returns a slice with all the elements of a that match string s.

func FilterFunc

func FilterFunc(a []string, f ValueFunc) []string

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

func FilterPrefix(a []string, prefix string) []string

FilterPrefix returns a slice with all the elements of a that have prefix.

func FilterSuffix

func FilterSuffix(a []string, suffix string) []string

FilterSuffix returns a slice with all the elements of a that have suffix.

func Index

func Index(a []string, s string) int

Index returns the index of the first instance of s in a, or -1 if not found

func IndexAny

func IndexAny(a, b []string) int

IndexAny returns the index of the first instance of b in a, or -1 if not found

func IndexFunc

func IndexFunc(a []string, f ValueFunc) int

IndexFunc returns the index of the first element in a where f(s) == true, or -1 if not found.

func InsertAt

func InsertAt(a []string, idx int, values ...string) []string

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 Intersect

func Intersect(a, b []string) []string

Intersect returns a slice with all the elements of b that are found in b.

func LastIndex

func LastIndex(a []string, s string) int

LastIndex returns the index of the last instance of s in a, or -1 if not found

func LastIndexAny

func LastIndexAny(a, b []string) int

LastIndexAny returns the index of the last instance of b in a, or -1 if not found

func LastIndexFunc

func LastIndexFunc(a []string, f ValueFunc) int

LastIndexFunc returns the index of the last element in a where f(s) == true, or -1 if not found.

func LastSearch

func LastSearch(a []string, substr string) int

LastSearch returns the index of the last element containing substr in a, or -1 if not found. An empty substr matches any.

func Map

func Map(mapping func(string) string, a []string) []string

Map returns a new slice with the function 'mapping' applied to each element of b

func Merge

func Merge(aa ...[]string) []string

Merge combines zero or many slices together, while preserving the order of elements.

func Pop

func Pop(a *[]string) string

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

func Push(a *[]string, values ...string) int

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

func Rand(a []string, n int) []string

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

func RandFunc(a []string, n int, f func(int) int) []string

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

func Reduce(a []string, f func(string, int, string) string) string

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 Repeat

func Repeat(s string, count int) []string

Repeat returns a slice consisting of count copies of s.

func RepeatFunc added in v1.0.1

func RepeatFunc(f func() string, count int) []string

RepeatFunc applies func f and returns a slice consisting of count values.

func Replace

func Replace(a []string, old, new string, n int) []string

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

func ReplaceAll(a []string, old, new string) []string

ReplaceAll returns a copy of the slice a with all instances of old replaced by new.

func Reverse

func Reverse(a []string) []string

Reverse returns a slice of the reverse index order elements of a.

func Search(a []string, substr string) int

Search returns the index of the first element containing substr in a, or -1 if not found. An empty substr matches any.

func Shift

func Shift(a *[]string) string

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

func Shuffle(a []string) []string

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

func Slice(a []string, offset, length int) []string

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

func Splice(a []string, offset, length int, b ...string) []string

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

func Split(a []string, sep string) [][]string

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

func SplitN(a []string, sep string, n int) [][]string

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 Trim

func Trim(a []string, s string) []string

Trim returns a slice with all the elements of a that don't match string s.

func TrimFunc

func TrimFunc(a []string, f ValueFunc) []string

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

func TrimPrefix(a []string, prefix string) []string

TrimPrefix returns a slice with all the elements of a that don't have prefix.

func TrimSuffix

func TrimSuffix(a []string, suffix string) []string

TrimSuffix returns a slice with all the elements of a that don't have suffix.

func Unique

func Unique(a []string) []string

Unique returns a slice with duplicate values removed.

func Unshift

func Unshift(a *[]string, s ...string) int

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

func Walk(a []string, f func(idx int, val string))

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

type ValueFunc func(v string) bool

ValueFunc is a value comparison func, used to compare element values in a slice.

func ValueContains added in v1.0.1

func ValueContains(substr string) ValueFunc

ValueContains returns true if element value v contains substr.

func ValueEquals added in v1.0.1

func ValueEquals(s string) ValueFunc

ValueEquals returns true if element value v equals s.

func ValueHasPrefix added in v1.0.1

func ValueHasPrefix(prefix string) ValueFunc

ValueHasPrefix returns true if element value begins with prefix.

func ValueHasSuffix added in v1.0.1

func ValueHasSuffix(suffix string) ValueFunc

ValueHasPrefix returns true if element value ends with suffix.

Jump to

Keyboard shortcuts

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