slices

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2022 License: MIT Imports: 9 Imported by: 53

README

genesis/slices

Package slices provides generic functions for slices.

The package is inspired by Enum and List Elixir modules.

Available functions:

  1. AllAsync
  2. AnyAsync
  3. EachAsync
  4. FilterAsync
  5. MapAsync
  6. ReduceAsync
  7. Choice
  8. ChunkEvery
  9. Contains
  10. Count
  11. Copy
  12. Cycle
  13. Dedup
  14. Delete
  15. DeleteAll
  16. DeleteAt
  17. DropEvery
  18. EndsWith
  19. Equal
  20. Grow
  21. Shrink
  22. Join
  23. Index
  24. InsertAt
  25. Intersperse
  26. Last
  27. Max
  28. Min
  29. Permutations
  30. Product
  31. Reverse
  32. Repeat
  33. Same
  34. Shuffle
  35. Sort
  36. Sorted
  37. Split
  38. StartsWith
  39. Sum
  40. TakeEvery
  41. TakeRandom
  42. ToChannel
  43. ToMap
  44. ToKeys
  45. Uniq
  46. Window
  47. Without
  48. Wrap
  49. Any
  50. All
  51. CountBy
  52. EqualBy
  53. ChunkBy
  54. DedupBy
  55. DropWhile
  56. Each
  57. EachErr
  58. Filter
  59. Find
  60. FindIndex
  61. GroupBy
  62. IndexBy
  63. Map
  64. Reduce
  65. ReduceWhile
  66. Reject
  67. Scan
  68. TakeWhile
  69. Concat
  70. Product2
  71. Zip

Documentation

Overview

Package slices provides generic functions for slices.

The package is inspired by `Enum` and `List` Elixir modules.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrEmpty = errors.New("container is empty")

ErrEmpty is an error for empty slice when it's expected to have elements

View Source
var ErrNegativeValue = errors.New("negative value passed")

ErrNegativeValue is an error for passed index <0

View Source
var ErrNonPositiveValue = errors.New("value must be positive")

ErrNonPositiveValue is an error for passed step <=0

View Source
var ErrNotFound = errors.New("given element is not found")

ErrNotFound is an error for case when given element is not found

View Source
var ErrOutOfRange = errors.New("index is bigger than container size")

ErrOutOfRange is an error that for index bigger than slice size

Functions

func All

func All[S ~[]T, T any](items S, f func(el T) bool) bool

All returns true if f returns true for all elements in arr

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	even := func(item int) bool { return item%2 == 0 }
	result := slices.All([]int{2, 4, 6}, even)
	fmt.Println(result)
	result = slices.All([]int{2, 4, 5}, even)
	fmt.Println(result)

}
Output:

true
false

func AllAsync

func AllAsync[S ~[]T, T any](items S, workers int, f func(el T) bool) bool

AllAsync returns true if f returns true for all elements in slice.

This is an asynchronous function. It will spawn as many goroutines as you specify in the `workers` argument. Set it to zero to spawn a new goroutine for each item.

func Any

func Any[S ~[]T, T any](items S, f func(el T) bool) bool

Any returns true if f returns true for any element in arr

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	even := func(item int) bool { return item%2 == 0 }
	result := slices.Any([]int{1, 2, 3}, even)
	fmt.Println(result)
	result = slices.Any([]int{1, 3, 5}, even)
	fmt.Println(result)
}
Output:

true
false

func AnyAsync

func AnyAsync[S ~[]T, T any](items S, workers int, f func(el T) bool) bool

AnyAsync returns true if f returns true for any element from slice

This is an asynchronous function. It will spawn as many goroutines as you specify in the `workers` argument. Set it to zero to spawn a new goroutine for each item.

func Choice

func Choice[S ~[]T, T any](items S, seed int64) (T, error)

Choice chooses a random element from the slice. If seed is zero, UNIX timestamp will be used.

func ChunkBy

func ChunkBy[S ~[]T, T comparable, G comparable](items S, f func(el T) G) []S

ChunkBy splits arr on every element for which f returns a new value.

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{1, 3, 4, 6, 8, 9}
	remainder := func(item int) int { return item % 2 }
	result := slices.ChunkBy(s, remainder)
	fmt.Println(result)
}
Output:

[[1 3] [4 6 8] [9]]

func ChunkEvery

func ChunkEvery[S ~[]T, T any](items S, count int) ([]S, error)

ChunkEvery returns slice of slices containing count elements each

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{1, 1, 2, 3, 5, 8, 13}
	result, _ := slices.ChunkEvery(s, 3)
	fmt.Println(result)
}
Output:

[[1 1 2] [3 5 8] [13]]

func Concat

func Concat[S ~[]T, T any](slices ...S) S

Concat concatenates given slices into a single slice.

func Contains

func Contains[S ~[]T, T comparable](items S, el T) bool

Contains returns true if el in arr.

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{2, 4, 6, 8}
	result := slices.Contains(s, 4)
	fmt.Println(result)
	result = slices.Contains(s, 3)
	fmt.Println(result)

}
Output:

true
false

func Copy

func Copy[S ~[]T, T any](items S) S

Copy creates a copy of the given slice.

func Count

func Count[S ~[]T, T comparable](items S, el T) int

Count return count of el occurrences in arr.

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{1, 0, 1, 0, 0, 1, 1, 0, 1, 0}
	result := slices.Count(s, 1)
	fmt.Println(result)
}
Output:

5

func CountBy

func CountBy[S ~[]T, T any](items S, f func(el T) bool) int

CountBy returns how many times f returns true.

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{1, 2, 3, 4, 5, 6}
	even := func(item int) bool { return item%2 == 0 }
	result := slices.CountBy(s, even)
	fmt.Println(result)
}
Output:

3

func Cycle

func Cycle[S ~[]T, T any](items S) chan T

Cycle is an infinite loop over slice

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/channels"
	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{1, 2, 3}
	c := slices.Cycle(s)
	c = channels.Take(c, 5)
	result := channels.ToSlice(c)
	fmt.Println(result)
}
Output:

[1 2 3 1 2]

func Dedup

func Dedup[S ~[]T, T comparable](items S) S

Dedup returns a given slice without consecutive duplicated elements

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{1, 2, 2, 3, 3, 3, 2, 3, 1, 1}
	result := slices.Dedup(s)
	fmt.Println(result)
}
Output:

[1 2 3 2 3 1]

func DedupBy

func DedupBy[S ~[]T, T comparable, G comparable](items S, f func(el T) G) S

DedupBy returns a given slice without consecutive elements For which f returns the same result

func Delete

func Delete[S ~[]T, T comparable](items S, element T) S

Delete deletes the first occurrence of the element from the slice

func DeleteAll

func DeleteAll[S ~[]T, T comparable](items S, element T) S

DeleteAll deletes all occurrences of the element from the slice

func DeleteAt

func DeleteAt[S ~[]T, T any](items S, indices ...int) (S, error)

DeleteAt returns the slice without elements on given positions

func DropEvery

func DropEvery[S ~[]T, T any](items S, nth int, from int) (S, error)

DropEvery returns a slice of every nth element in the enumerable dropped, starting with the first element.

func DropWhile

func DropWhile[S ~[]T, T any](items S, f func(el T) bool) S

DropWhile drops elements from arr while f returns true

func Each

func Each[S ~[]T, T any](items S, f func(el T))

Each calls f for every element from arr

func EachAsync

func EachAsync[S ~[]T, T any](items S, workers int, f func(el T))

EachAsync calls f for every element from slice

This is an asynchronous function. It will spawn as many goroutines as you specify in the `workers` argument. Set it to zero to spawn a new goroutine for each item.

func EachErr

func EachErr[S ~[]E, E any](items S, f func(el E) error) error

EachErr calls f for every element from arr until f returns an error

func EndsWith

func EndsWith[S ~[]T, T comparable](items S, suffix S) bool

EndsWith returns true if slice ends with the given suffix slice. If suffix is empty, it returns true.

func Equal

func Equal[S1 ~[]T, S2 ~[]T, T comparable](items S1, other S2) bool

Equal returns true if slices are equal

func EqualBy

func EqualBy[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool

EqualBy returns true if the cmp function returns true for any elements of the slices in the matching positions. If len of the slices is different, false is returned. It is similar to Any except it Zip's by two slices.

func Filter

func Filter[S ~[]T, T any](items S, f func(el T) bool) S

Filter returns slice of T for which F returned true

func FilterAsync

func FilterAsync[S ~[]T, T any](items S, workers int, f func(el T) bool) S

FilterAsync returns slice of element for which f returns true

This is an asynchronous function. It will spawn as many goroutines as you specify in the `workers` argument. Set it to zero to spawn a new goroutine for each item.

The resulting items have the same order as in the input slice.

func Find

func Find[S ~[]T, T any](items S, f func(el T) bool) (T, error)

Find returns the first element for which f returns true

func FindIndex

func FindIndex[S ~[]T, T any](items S, f func(el T) bool) int

FindIndex is like Find, but return element index instead of element itself. Returns -1 if element not found

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	type UserId int
	index := slices.FindIndex(
		[]UserId{1, 2, 3, 4, 5},
		func(el UserId) bool { return el == 3 },
	)
	fmt.Println(index)
}
Output:

2

func GroupBy

func GroupBy[S ~[]T, T any, G constraints.Ordered](items S, f func(el T) G) map[G]S

GroupBy groups element from array by value returned by f

func Grow

func Grow[S ~[]T, T any](items S, n int) S

Grow increases the slice's by n elements. So, for cap(slice)=8 and n=2, the result will have cap at least 10. The function can be used to reduce allocations when inserting more elements into an existing slice.

func Index

func Index[S []T, T comparable](items S, item T) (int, error)

Index returns the index of the first occurrence of item in items.

func IndexBy

func IndexBy[S []T, T comparable](items S, f func(T) bool) (int, error)

IndexBy returns the first index in items for which f returns true.

func InsertAt

func InsertAt[S ~[]T, T any](items S, index int, item T) (S, error)

InsertAt returns the items slice with the item inserted at the given index.

func Intersperse

func Intersperse[S ~[]T, T any](items S, el T) S

Intersperse inserts el between each element of arr

func Join

func Join[S ~[]T, T any](items S, sep string) string

Join concatenates elements of the slice to create a single string.

func Last

func Last[S ~[]T, T any](items S) (T, error)

Last returns the last element from the slice

func Map

func Map[S ~[]T, T any, G any](items S, f func(el T) G) []G

Map applies F to all elements in slice of T and returns slice of results

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{4, 8, 15, 16, 23, 42}
	double := func(el int) int { return el * 2 }
	doubled := slices.Map(s, double)
	fmt.Println(doubled)
}
Output:

[8 16 30 32 46 84]

func MapAsync

func MapAsync[S ~[]T, T any, G any](items S, workers int, f func(el T) G) []G

MapAsync applies F to all elements in slice of T and returns slice of results

This is an asynchronous function. It will spawn as many goroutines as you specify in the `workers` argument. Set it to zero to spawn a new goroutine for each item.

The result items have the same order as in the input slice.

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	pages := slices.MapAsync(
		[]string{"google.com", "go.dev", "golang.org"},
		0,
		func(url string) string {
			return fmt.Sprintf("<web page for %s>", url)
		},
	)
	fmt.Println(pages)
	// [<web page for google.com> <web page for go.dev> <web page for golang.org>]
}
Output:

func Max

func Max[S ~[]T, T constraints.Ordered](items S) (T, error)

Max returns the maximal element from arr

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{7, 42, 13}
	max, _ := slices.Max(s)
	fmt.Println(max)
}
Output:

42

func Min

func Min[S ~[]T, T constraints.Ordered](items S) (T, error)

Min returns the minimal element from arr

Example
package main

import (
	"fmt"

	"github.com/life4/genesis/slices"
)

func main() {
	s := []int{42, 7, 13}
	min, _ := slices.Min(s)
	fmt.Println(min)
}
Output:

7

func Permutations

func Permutations[T any](items []T, size int) chan []T

Permutations returns successive size-length permutations of elements from the slice. {1, 2, 3} -> {1, 2}, {1, 3}, {2, 1}, {2, 3}, {3, 1}, {3, 2}

func Product

func Product[S ~[]T, T any](items S, repeat int) chan []T

Product returns cortesian product of elements {{1, 2}, {3, 4}} -> {1, 3}, {1, 4}, {2, 3}, {2, 4}

func Product2

func Product2[T any](items ...[]T) chan []T

Product returns cortesian product of elements {{1, 2}, {3, 4}} -> {1, 3}, {1, 4}, {2, 3}, {2, 4}

func Reduce

func Reduce[S ~[]T, T any, G any](items S, acc G, f func(el T, acc G) G) G

Reduce applies F to acc and every element in slice of T and returns acc

func ReduceAsync

func ReduceAsync[S ~[]T, T any](items S, workers int, f func(left T, right T) T) T

ReduceAsync reduces slice to a single value with f.

This is an asynchronous function. It will spawn as many goroutines as you specify in the `workers` argument. Set it to zero to spawn a new goroutine for each item.

The function is guaranteed to be called with neighbored items. However, it may be called out of order. The results are collected into a new slice which is reduced again, until only one item remains. You can think about it as a piramid. On each iteration, 2 elements ar taken and merged together until only one remains.

An example for sum:

``` 1 2 3 4 5

3   7  5
 10    5
    15

```

func ReduceWhile

func ReduceWhile[S ~[]T, T any, G any](items S, acc G, f func(el T, acc G) (G, error)) (G, error)

ReduceWhile is like Reduce, but stops when f returns error

func Reject

func Reject[S ~[]T, T any](items S, f func(el T) bool) S

Reject is like filter but it returns slice of T for which F returned false

func Repeat

func Repeat[S ~[]T, T any](items S, n int) S

Repeat repeats items slice n times.

func Reverse

func Reverse[S ~[]T, T any](items S) S

Reverse returns given arr in reversed order

func Same

func Same[S ~[]T, T comparable](items S) bool

Same returns true if all element in arr the same

func Scan

func Scan[S ~[]T, T any, G any](items S, acc G, f func(el T, acc G) G) []G

Scan is like Reduce, but returns slice of f results

func Shrink

func Shrink[S ~[]T, T any](items S) S

Shrink removes unused capacity from the slice.

func Shuffle

func Shuffle[S ~[]T, T any](items S, seed int64)

Shuffle in random order the given elements

This is an in-place operation, it modifies the passed slice.

func Sort

func Sort[S ~[]T, T constraints.Ordered](items S) S

Sort returns sorted slice

func Sorted

func Sorted[S ~[]T, T constraints.Ordered](items S) bool

Sorted returns true if slice is sorted

func Split

func Split[S ~[]T, T comparable](items S, sep T) []S

Split splits arr by sep

func StartsWith

func StartsWith[S ~[]T, T comparable](items S, prefix S) bool

StartsWith returns true if slice starts with the given prefix slice. If prefix is empty, it returns true.

func Sum

func Sum[S ~[]T, T constraints.Ordered](items S) T

Sum return sum of all elements from arr

func TakeEvery

func TakeEvery[S ~[]T, T any](items S, nth int, from int) (S, error)

TakeEvery returns slice of every nth elements

func TakeRandom

func TakeRandom[S ~[]T, T any](items S, count int, seed int64) (S, error)

TakeRandom returns slice of count random elements from the slice

func TakeWhile

func TakeWhile[S ~[]T, T any](items S, f func(el T) bool) S

TakeWhile takes elements from arr while f returns true

func ToChannel

func ToChannel[S ~[]T, T any](items S) chan T

ToChannel returns channel with elements from the slice

func ToKeys

func ToKeys[S ~[]K, K comparable, V any](items S, val V) map[K]V

ToKeys converts the given slice into a map where items from the slice are the keys of the resulting map and all values are equal to the given `val` value.

func ToMap

func ToMap[S ~[]V, V any](items S) map[int]V

ToMap converts the given slice into a map where keys are indices and values are items from the given slice.

func Uniq

func Uniq[S ~[]T, T comparable](items S) S

Uniq returns arr with only first occurrences of every element.

func Window

func Window[S ~[]T, T any](items S, size int) ([]S, error)

Window makes sliding window for a given slice: ({1,2,3}, 2) -> (1,2), (2,3)

func Without

func Without[S ~[]T, T comparable](items S, elements ...T) S

Without returns the slice with filtered out element

func Wrap

func Wrap[T any](item T) []T

Wrap makes a single element slice out of the given value

func Zip

func Zip[S ~[]T, T any](items ...S) chan S

Zip returns chan of arrays of elements from given arrs on the same position.

Types

This section is empty.

Jump to

Keyboard shortcuts

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