slices

package
v1.10.3 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 9 Imported by: 55

README

genesis/slices

Package slices provides generic functions for slices.

The package is inspired by Enum and List Elixir modules.

Documentation

Overview

🍞 Package slices provides generic functions for slices.

The package is inspired by Enum and List Elixir modules.

Conventions

  • All functions accepting a slice accept it as the very first argument.
  • If a function provides 2 implementations one of which accepts a function (for example, Equal and EqualBy), the one accepting the function has suffix "By".
  • If a function is concurrent, it has suffix "Async".
  • Almost all functions are pure and don't modify the given slice. The only exception so far is Shuffle.

Functions

This package has a lot of functions and it might be hard to find what you need if you don't know how it is called. Because of that, this section provides an easier to navigate list of all functions defined here. Each of them is grouped based on the return type.

Also, for easier visual navigation, a signature is provided for each function where instead of argument type and name an emoji is used:

  • 📚 is a slice
  • 📕 is a slice element
  • 💬 is a function
  • ❓ is a bool
  • 📺 is a channel
  • 🗺 is a map
  • 💥 is an error
  • 🔢 is an int
  • 🎲 is a randomization seed
  • 🧑‍🔧️ is a number of workers

🎲 Randomization functions:

❓ Functions returning a bool:

🗺 Functions returning a map:

📺 Functions returning a channel:

📕 Functions returning a single item:

  • Find(📚, 💬) (📕, 💥)
  • Last(📚) (📕, 💥)
  • Max(📚) (📕, 💥)
  • Min(📚) (📕, 💥)
  • Reduce(📚, 📕, 💬) 📕
  • ReduceAsync(📚, 🧑‍🔧️, 💬) 📕
  • ReduceWhile(📚, 📕, 💬) (📕, 💥)
  • Sum(📚) 📕

🔢 Functions returning an int:

🖨 Functions that take a slice and return a slice:

📚 Functions returning a new slice:

😶 Functions returning a something else or nothing:

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 items.

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 items.

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.

Example
package main

import (
	"fmt"

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

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

true

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 item in items.

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 in items.

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.

Example
package main

import (
	"fmt"

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

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

true

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.

Example
package main

import (
	"fmt"

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

func main() {
	result, _ := slices.Choice([]int{3, 4, 5, 6}, 13)
	fmt.Println(result)
}
Output:

3

func ChunkBy

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

ChunkBy splits items 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 splits items into groups of length count.

If items can't be split evenly, the final chunk will contain the remaining elements.

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 the given slices into a single slice.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, 5}
	s2 := []int{6, 7, 8}
	result := slices.Concat(s1, s2)
	fmt.Println(result)
}
Output:

[3 4 5 6 7 8]

func Contains

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

Contains returns true if el is in items.

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.

Example
package main

import (
	"fmt"

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

func main() {
	orig := []int{3, 4}
	copy := slices.Copy(orig)
	orig = append(orig, 5)
	copy = append(copy, 6)
	fmt.Println(orig)
	fmt.Println(copy)
}
Output:

[3 4 5]
[3 4 6]

func Count

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

Count return the count of el occurrences in items.

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 items.

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 items 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 any, G comparable](items S, f func(el T) G) S

DedupBy returns a copy of items, but without consecutive elements for which f returns the same result.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{1, 2, -2, -3, 3, -3, 2, 3, 1, 1}
	abs := func(x int) int {
		if x < 0 {
			return -x
		}
		return x
	}
	result := slices.DedupBy(s, abs)
	fmt.Println(result)
}
Output:

[1 2 -3 2 3 1]

func Delete

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

Delete deletes the first occurrence of the element from items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 3, 4, 5}
	result := slices.Delete(s, 4)
	fmt.Println(result)
}
Output:

[3 5 3 4 5]

func DeleteAll

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

DeleteAll deletes all occurrences of the element from items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 3, 4, 5}
	result := slices.DeleteAll(s, 3)
	fmt.Println(result)
}
Output:

[4 5 4 5]

func DeleteAt

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

DeleteAt returns items without the elements in indices.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 3, 4, 5}
	result, _ := slices.DeleteAt(s, 1, 3)
	fmt.Println(result)
}
Output:

[3 5 4 5]

func Difference added in v1.9.0

func Difference[S1 ~[]T, S2 ~[]T, T comparable](target S1, exclude S2) []T

Difference returns a slice containing elements from target that are not in exclude.

The items in the result slice appear in the same order as in the first given slice. Each item appears only once.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, 4, 5, 6, 6, 7}
	s2 := []int{5, 5, 4, 8}
	result := slices.Difference(s1, s2)
	fmt.Println(result)
}
Output:

[3 6 7]

func DropEvery

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

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

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8}
	result, _ := slices.DropEvery(s, 2, 0)
	fmt.Println(result)
}
Output:

[4 6 8]

func DropWhile

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

DropWhile drops elements from the start of items while f returns true.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{2, 4, 6, 7, 8, 9, 10}
	even := func(x int) bool { return x%2 == 0 }
	result := slices.DropWhile(s, even)
	fmt.Println(result)
}
Output:

[7 8 9 10]

func DropZero added in v1.9.0

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

DropZero returns a slice with every default value removed.

For example, for a slice of pointers it will drop nils, for a slice of ints it will drop zero, and for a slice of strings it will drop empty strings.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 0, 6, 0, 0}
	result := slices.DropZero(s)
	fmt.Println(result)
}
Output:

[4 5 6]

func Each

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

Each calls f for each item in items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6}
	slices.Each(s, func(x int) {
		fmt.Println(x * 2)
	})
}
Output:

8
10
12

func EachAsync

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

EachAsync calls f for each element in items.

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.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6}
	sum := 0
	slices.EachAsync(s, 0, func(x int) {
		sum += x
	})
	fmt.Println(sum)
}
Output:

15

func EachErr

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

EachErr calls f for each element in items until f returns an error.

Example
package main

import (
	"errors"
	"fmt"

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

func main() {
	s := []int{4, 5, 6, 7, 8}
	err := slices.EachErr(s, func(x int) error {
		if x == 6 {
			return errors.New("six found")
		}
		fmt.Println(x * 2)
		return nil
	})
	fmt.Println(err)
}
Output:

8
10
six found

func EndsWith

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

EndsWith returns true if items ends with the given suffix slice.

If suffix is empty, it returns true.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8}
	result := slices.EndsWith(s, []int{7, 8})
	fmt.Println(result)
}
Output:

true

func Equal

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

Equal returns true if the slices are equal.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, 5}
	s2 := []int{3, 4, 5, 6}
	result := slices.Equal(s1, s2)
	fmt.Println(result)
}
Output:

false

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 all element pairs in the two slices.

If the slices are different lengths, false is returned.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, -5}
	s2 := []int{3, -4, 5}
	absEq := func(a, b int) bool {
		if a < 0 {
			a = -a
		}
		if b < 0 {
			b = -b
		}
		return a == b
	}
	result := slices.EqualBy(s1, s2, absEq)
	fmt.Println(result)
}
Output:

true

func Filter

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

Filter returns a slice containing only items where f returns true.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6, 7, 8, 10, 12, 13}
	even := func(x int) bool { return x%2 == 0 }
	result := slices.Filter(s, even)
	fmt.Println(result)
}
Output:

[4 6 8 10 12]

func FilterAsync

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

FilterAsync returns a slice containing only items where 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.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6, 7, 8, 10, 12, 13}
	even := func(x int) bool { return x%2 == 0 }
	result := slices.FilterAsync(s, 0, even)
	fmt.Println(result)
}
Output:

[4 6 8 10 12]

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.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{5, 7, 9, 4, 3, 6}
	even := func(x int) bool { return x%2 == 0 }
	result, _ := slices.Find(s, even)
	fmt.Println(result)
}
Output:

4

func FindIndex

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

FindIndex returns the index of the first element for which f returns true. Returns -1 if no matching element is 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, K comparable](items S, f func(el T) K) map[K]S

GroupBy groups items by the value returned by f.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 13, 14, 15, 23, 33}
	even := func(x int) int { return x % 10 }
	result := slices.GroupBy(s, even)
	fmt.Println(result)
}
Output:

map[3:[3 13 23 33] 4:[4 14] 5:[5 15]]

func Grow

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

Grow increases the slice capacity to fit at least n more elements.

So, for len(slice)=8 and n=2, the result will have a capacity of at least 10.

The function can be used to reduce allocations when inserting more elements into an existing slice.

If the slice already has sufficient capacity, this slice is returned unmodified.

Example
package main

import (
	"fmt"

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

func main() {
	s := make([]int, 1, 4)
	fmt.Printf("Before: len=%d, cap=%d\n", len(s), cap(s))
	r := slices.Grow(s, 5)
	fmt.Printf("After:  len=%d, cap=%d\n", len(r), cap(r))
}
Output:

Before: len=1, cap=4
After:  len=1, cap=8

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.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	index, _ := slices.Index(s, 4)
	fmt.Println(index)
}
Output:

1

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.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{5, 7, 9, 8, 3, 6}
	even := func(x int) bool { return x%2 == 0 }
	result, _ := slices.IndexBy(s, even)
	fmt.Println(result)
}
Output:

3

func InsertAt

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

InsertAt returns items with item inserted at the given index.

If index is beyond the length of items, ErrOutOfRange is returned. If index is negative, ErrNegativeValue is returned.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	result, _ := slices.InsertAt(s, 1, 6)
	fmt.Println(result)
}
Output:

[3 6 4 5]

func Intersect added in v1.9.0

func Intersect[S1 ~[]T, S2 ~[]T, T comparable](items1 S1, items2 S2) []T

Intersect returns items that appear in both slices.

The items in the result slice appear in the same order as in the first given slice. Each item appears only once.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, 5, 5, 6, 6, 7}
	s2 := []int{6, 5, 5, 4, 8}
	result := slices.Intersect(s1, s2)
	fmt.Println(result)
}
Output:

[4 5 6]

func Intersect2 added in v1.8.0

func Intersect2[S1 ~[]T, S2 ~[]T, T comparable](items1 S1, items2 S2) []T

Intersect2 is an alias for Intersect

DEPRECATED. Use Intersect instead.

func Intersperse

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

Intersperse inserts el between each element of items.

Example
package main

import (
	"fmt"

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

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

[3 1 4 1 5]

func Join

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

Join concatenates elements of items to create a single string.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	result := slices.Join(s, "; ")
	fmt.Println(result)
}
Output:

3; 4; 5

func Last

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

Last returns the last element from items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	result, _ := slices.Last(s)
	fmt.Println(result)
}
Output:

5

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 items and returns a slice of the 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 items and returns a slice of the 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)
}
Output:

[<web page for google.com> <web page for go.dev> <web page for golang.org>]

func MapFilter added in v1.3.0

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

MapFilter applies f to all elements in items, and returns a filtered slice of the results.

f returns two values: the mapped value, and a boolean indicating whether the result should be included in the filtered slice.

Example
package main

import (
	"fmt"
	"strconv"

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

func main() {
	s := []int{4, 8, 15, 16, 23, 42}
	isEven := func(t int) (string, bool) {
		if t%2 == 0 {
			s := strconv.Itoa(t)
			return s, true
		} else {
			return "", false
		}

	}
	doubled := slices.MapFilter(s, isEven)
	fmt.Println(doubled)
}
Output:

[4 8 16 42]

func Max

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

Max returns the maximal element in items.

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 items.

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 Partition added in v1.9.0

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

Partition splits items into two slices based on if f returns true or false.

The first returned slice contains the items for which f returned true. The second returned slice contains the remainder. Order is preserved in both slices.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6, 7, 8, 8, 7}
	isEven := func(x int) bool { return x%2 == 0 }
	even, odd := slices.Partition(s, isEven)
	fmt.Println(even)
	fmt.Println(odd)
}
Output:

[4 6 8 8]
[5 7 7]

func Permutations

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

Permutations returns successive size-length permutations of elements from items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{1, 2, 3}
	ch := slices.Permutations(s, 2)
	result := make([][]int, 0)
	for x := range ch {
		result = append(result, x)
	}
	fmt.Println(result)
}
Output:

[[1 2] [1 3] [2 1] [2 3] [3 1] [3 2]]

func Prepend added in v1.9.0

func Prepend[S ~[]T, T any](target S, items ...T) S

Prepend returns the target slice with the given items added at the beginning.

Example
package main

import (
	"fmt"

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

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

[2 3 4 5 6]

func Product

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

Product returns the cartesian product of items to itself, repeat times.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{1, 2, 3}
	ch := slices.Product(s, 2)
	result := make([][]int, 0)
	for x := range ch {
		result = append(result, x)
	}
	fmt.Println(result)
}
Output:

[[1 1] [1 2] [1 3] [2 1] [2 2] [2 3] [3 1] [3 2] [3 3]]

func Product2

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

Product2 returns the cartesian product of elements in the given slices.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{1, 2}
	s2 := []int{3, 4}
	ch := slices.Product2(s1, s2)
	result := make([][]int, 0)
	for x := range ch {
		result = append(result, x)
	}
	fmt.Println(result)
}
Output:

[[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 each element in items, reducing the slice to a single value.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	sum := func(a, b int) int {
		fmt.Printf("Received %d and %d\n", a, b)
		return a + b
	}
	result := slices.Reduce(s, 0, sum)
	fmt.Printf("Result is %d\n", result)
}
Output:

Received 3 and 0
Received 4 and 3
Received 5 and 7
Result is 12

func ReduceAsync

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

ReduceAsync reduces items 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
Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	sum := func(a, b int) int { return a + b }
	result := slices.ReduceAsync(s, 0, sum)
	fmt.Println(result)
}
Output:

12

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 an error.

Example
package main

import (
	"errors"
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6}
	sum := func(a, b int) (int, error) {
		fmt.Printf("Received %d and %d\n", a, b)
		if a == 6 {
			return b, errors.New("got six")
		}
		return a + b, nil
	}
	result, err := slices.ReduceWhile(s, 0, sum)
	fmt.Printf("Result is %d\n", result)
	fmt.Printf("Error is '%v'\n", err)
}
Output:

Received 3 and 0
Received 4 and 3
Received 5 and 7
Received 6 and 12
Result is 12
Error is 'got six'

func Reject

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

Reject returns a slice containing only items where f returns false. It is the opposite of Filter.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6, 7, 8, 10, 12, 13}
	odd := func(x int) bool { return x%2 == 1 }
	result := slices.Reject(s, odd)
	fmt.Println(result)
}
Output:

[4 6 8 10 12]

func Repeat

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

Repeat repeats items n times.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6}
	result := slices.Repeat(s, 3)
	fmt.Println(result)
}
Output:

[4 5 6 4 5 6 4 5 6]

func Replace added in v1.9.0

func Replace[S ~[]T, T comparable, I constraints.Integer](items S, start, end I, item T) (S, error)

Replace replaces elements in items from start to end with the given item.

The item with the end index is not replaced.

Result:

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{4, 5, 6, 7}
	result, _ := slices.Replace(s, 1, 3, 9)
	fmt.Println(result)
}
Output:

[4 9 9 7]

func Reverse

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

Reverse returns items in reversed order.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	result := slices.Reverse(s)
	fmt.Println(result)
}
Output:

[5 4 3]

func Same

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

Same returns true if all elements in items are the same.

Example
package main

import (
	"fmt"

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

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

true

func Scan

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

Scan applies f to acc and each element in items, feeding the output of the last call into the next call, and returning a slice of the results.

Scan is like Reduce, but it returns a slice of the results instead of a single value.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	sum := func(a, b int) int { return a + b }
	result := slices.Scan(s, 0, sum)
	fmt.Println(result)
}
Output:

[3 7 12]

func Shrink

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

Shrink removes unused capacity from the slice.

In other words, the returned slice has capacity equal to length.

Example
package main

import (
	"fmt"

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

func main() {
	s := make([]int, 1, 4)
	fmt.Printf("Before: len=%d, cap=%d\n", len(s), cap(s))
	r := slices.Shrink(s)
	fmt.Printf("After:  len=%d, cap=%d\n", len(r), cap(r))
}
Output:

Before: len=1, cap=4
After:  len=1, cap=1

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.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8}
	slices.Shuffle(s, 13)
	fmt.Println(s)
}
Output:

[7 8 5 3 6 4]

func Sort

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

Sort returns a sorted copy of items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{7, 6, 8, 5, 3, 6, 4}
	result := slices.Sort(s)
	fmt.Println(result)
}
Output:

[3 4 5 6 6 7 8]

func SortBy added in v1.9.0

func SortBy[S ~[]T, T any, K constraints.Ordered](items S, f func(el T) K) S

SortBy sorts items using the values returned by f.

The function might be called more than once for the same element. It is expected to be fast and always produce the same result.

The sort is stable. If two elements have the same ordering key, they are not swapped.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{7, -6, 6, 8, 5, 3, 6, 4}
	abs := func(x int) int {
		if x < 0 {
			return -x
		}
		return x
	}
	result := slices.SortBy(s, abs)
	fmt.Println(result)
}
Output:

[3 4 5 -6 6 6 7 8]

func Sorted

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

Sorted returns true if items is sorted.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 3, 4, 5, 5, 5, 6, 7, 7, 12, 15}
	result := slices.Sorted(s)
	fmt.Println(result)
}
Output:

true

func SortedUnique added in v1.9.0

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

SortedUnique returns true if items is sorted and all elements are unique.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8, 12, 16, 19}
	result := slices.SortedUnique(s)
	fmt.Println(result)
}
Output:

true

func Split

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

Split splits items by sep.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 1, 5, 1, 1, 6, 7, 1}
	result := slices.Split(s, 1)
	fmt.Println(result)
}
Output:

[[3 4] [5] [] [6 7] []]

func StartsWith

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

StartsWith returns true if items starts with prefix. If prefix is empty, StartsWith returns true.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8}
	result := slices.StartsWith(s, []int{3, 4})
	fmt.Println(result)
}
Output:

true

func Sum

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

Sum return sum of all elements in items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	result := slices.Sum(s)
	fmt.Println(result)
}
Output:

12

func TakeEvery

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

TakeEvery returns a slice containing every nth element in items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8}
	result, _ := slices.TakeEvery(s, 2, 0)
	fmt.Println(result)
}
Output:

[3 5 7]

func TakeRandom

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

TakeRandom returns a slice of count random elements from items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 7, 8}
	result, _ := slices.TakeRandom(s, 3, 13)
	fmt.Println(result)
}
Output:

[7 8 5]

func TakeWhile

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

TakeWhile takes elements from items while f returns true.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 5, 7, 8, 9, 10, 11}
	odd := func(x int) bool { return x%2 == 1 }
	result := slices.TakeWhile(s, odd)
	fmt.Println(result)
}
Output:

[3 5 7]

func ToChannel

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

ToChannel returns a channel with elements from items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	ch := slices.ToChannel(s)
	result := make([]int, 0)
	for x := range ch {
		result = append(result, x)
	}
	fmt.Println(result)
}
Output:

[3 4 5]

func ToKeys

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

ToKeys returns a map where the keys are the elements in items and all values are set to val.

Example
package main

import (
	"fmt"

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

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

map[3:2 4:2 5:2]

func ToMap

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

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

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5}
	result := slices.ToMap(s)
	fmt.Println(result)
}
Output:

map[0:3 1:4 2:5]

func ToMapGroupedBy added in v1.2.0

func ToMapGroupedBy[V any, T comparable](items []V, keyExtractor func(V) T) map[T][]V

ToMapGroupedBy is an alias for GroupBy.

DEPRECATED. Use GroupBy instead.

func Union added in v1.9.0

func Union[S ~[]T, T comparable](left S, right S) S

Union returns a slice of unique values from both slices preserving their order.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, 5, 5, 6, 6, 7}
	s2 := []int{6, 5, 5, 4, 8}
	result := slices.Union(s1, s2)
	fmt.Println(result)
}
Output:

[3 4 5 6 7 8]

func Uniq

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

Uniq returns items with only the first occurrence of each unique element.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 3, 4, 5, 4, 3, 3}
	result := slices.Uniq(s)
	fmt.Println(result)
}
Output:

[3 4 5]

func Unique added in v1.8.0

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

Unique returns true if each element in items appears only once.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 3}
	result := slices.Unique(s)
	fmt.Println(result)
}
Output:

false

func Window

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

Window makes a sliding window for items.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6}
	result, _ := slices.Window(s, 2)
	fmt.Println(result)
}
Output:

[[3 4] [4 5] [5 6]]

func Without

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

Without returns items without the given elements.

Example
package main

import (
	"fmt"

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

func main() {
	s := []int{3, 4, 5, 6, 3, 4, 5, 6, 7, 8}
	result := slices.Without(s, 4, 5)
	fmt.Println(result)
}
Output:

[3 6 3 6 7 8]

func Wrap

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

Wrap wraps item in a slice of the same type.

Example
package main

import (
	"fmt"

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

func main() {
	result := slices.Wrap(4)
	fmt.Println(result)
}
Output:

[4]

func Zip

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

Zip returns a chan of slices each containing elements from consecutive positions in each input slice. The first slice in the channel will contain items[0][0], items[1][0], ..., items[n-1][0]. The second slice in the channel will contain items[0][1], items[1][1], ..., items[n-1][1]. If the slices are of unequal length, the shortest slice length will be used.

Example
package main

import (
	"fmt"

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

func main() {
	s1 := []int{3, 4, 5}
	s2 := []int{6, 7, 8, 9}
	ch := slices.Zip(s1, s2)
	result := make([][]int, 0)
	for x := range ch {
		result = append(result, x)
	}
	fmt.Println(result)
}
Output:

[[3 6] [4 7] [5 8]]

Types

This section is empty.

Jump to

Keyboard shortcuts

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