dj

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2023 License: MIT Imports: 9 Imported by: 0

README

dj: For cleaner and safer Go code

CI Status GoDoc Go Report Card License

dj is a Go 1.18+ library that makes it easy to write clean and safe Go code.

Install

Simply go get the library:

go get github.com/go-dj/dj

Usage

Import dj and use it like so:

import (
    "fmt"

    "github.com/go-dj/dj"
)

func main() {
    vals := dj.RangeN(5)

    fmt.Println(vals) // [0 1 2 3 4]

    doubled := dj.MapEach(vals, func(val int) int {
        return val * 2
    })

    fmt.Println(doubled) // [0 2 4 6 8]
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func After added in v0.6.0

func After[T comparable](in []T, elem T) []T

After returns all elements in the given slice after the given element.

func AfterFn added in v0.6.0

func AfterFn[T any](in []T, fn func(T) bool) []T

AfterFn returns all elements in the given slice after the first element that satisfies the given function.

func All

func All[T any](slice []T, fn func(T) bool) bool

All returns true if the given predicate is true for all elements in the given slice.

func Any

func Any[T any](slice []T, fn func(T) bool) bool

Any returns true if the given predicate is true for any element in the given slice.

func AsRecv

func AsRecv[T any](ch ...chan T) []<-chan T

AsRecv converts the given channels to receive-only channels.

func AsSend

func AsSend[T any](ch ...chan T) []chan<- T

AsSend converts the given channels to send-only channels.

func BFS added in v0.3.0

func BFS[T any](root T, next func(T) []T, fn func(T))

BFS is a breadth-first search starting at the root node and traversing the graph using the next function.

func BFSCtx added in v0.3.0

func BFSCtx[T any](ctx context.Context, root T, next func(T) []T, fn func(T))

BFSCtx is a breadth-first search starting at the root node and traversing the graph using the next function. The context can be used to cancel the search.

func Before added in v0.6.0

func Before[T comparable](in []T, elem T) []T

Before returns all elements in the given slice before the given element.

func BeforeFn added in v0.6.0

func BeforeFn[T any](in []T, fn func(T) bool) []T

BeforeFn returns all elements in the given slice before the first element that satisfies the given function.

func BindCtx added in v0.9.0

func BindCtx(ctx context.Context, toCtx ...context.Context) context.Context

BindCtxAny binds the first given context to the rest of the given contexts. The returned context is cancelled once any of the given contexts are cancelled.

func Binomial added in v0.3.0

func Binomial(trials int, p float64) int

Binomial returns a random number from a binomial distribution with the given number of trials and probability of success.

func Chunk

func Chunk[T any](slice []T, size int) [][]T

Chunk chunks the given slice into slices of the given size.

func ChunkBy added in v0.13.0

func ChunkBy[T any](slice []T, cond ...ChunkCond[T]) [][]T

ChunkBy chunks the given slice into slices limited by the given conditions.

func ChunkChan added in v0.12.0

func ChunkChan[T any](ch <-chan T, n int) <-chan []T

ChunkChan chunks the given channel into a single channel. The returned channel is closed when the given channel is closed.

func ChunkChanCtx added in v0.12.0

func ChunkChanCtx[T any](ctx context.Context, ch <-chan T, n int) <-chan []T

ChunkChanCtx chunks the given channel into a single channel. The returned channel is closed when the given channel is closed or the context is canceled.

func Clone

func Clone[T any](v []T) []T

Clone returns a copy of the given slice.

func CloseChan

func CloseChan[T any](ch ...chan<- T)

CloseChan closes the given channels.

func CollectChan

func CollectChan[T any](ch <-chan T) []T

CollectChan reads all values from the channel.

func CollectChanCtx

func CollectChanCtx[T any](ctx context.Context, ch <-chan T) []T

CollectChanCtx reads all values from the channel. It stops reading when the context is canceled.

func Concat

func Concat[T any](in ...[]T) []T

Concat returns a slice containing the elements of the given slices.

func ConcatChan

func ConcatChan[T any](chs ...<-chan T) <-chan T

ConcatChan joins the given channels into a single channel. That is, the first channel is emptied, then the second, and so on. The returned channel is closed when all the given channels are closed.

func ConcatChanCtx

func ConcatChanCtx[T any](ctx context.Context, chs ...<-chan T) <-chan T

ConcatChanCtx joins the given channels into a single channel. That is, the first channel is emptied, then the second, and so on. The returned channel is closed when all the given channels are closed or the context is canceled.

func Contains

func Contains[T comparable](in []T, elem T) bool

Contains returns true if the given slice contains the given element.

func ContainsAll

func ContainsAll[T comparable](in []T, elems ...T) bool

ContainsAll returns true if the given slice contains all of the given elements.

func ContainsAny

func ContainsAny[T comparable](in []T, elems ...T) bool

ContainsAny returns true if the given slice contains any of the given elements.

func ContainsNone

func ContainsNone[T comparable](in []T, elems ...T) bool

ContainsNone returns true if the given slice contains none of the given elements.

func Count

func Count[T comparable](in []T, val T) int

Count returns the number of elements in the given slice that equal the given value.

func CountFn

func CountFn[T any](in []T, fn func(T) bool) int

CountFn returns the number of elements in the given slice that satisfy the given predicate.

func DFS added in v0.3.0

func DFS[T any](root T, next func(T) []T, fn func(T))

DFS is a depth-first search starting at the root node and traversing the graph using the next function.

func DFSCtx added in v0.3.0

func DFSCtx[T any](ctx context.Context, root T, next func(T) []T, fn func(T))

DFSCtx is a depth-first search starting at the root node and traversing the graph using the next function. The context can be used to cancel the search.

func Difference

func Difference[T comparable](a, b []T) []T

Difference returns a slice of the elements that are in the first slice but not the second.

func DifferenceFn

func DifferenceFn[T any](a, b []T, eq func(T, T) bool) []T

DifferenceFn returns a slice of the elements that are in the first slice but not the second, according to the given function.

func DropChan added in v0.7.0

func DropChan[T any](ch <-chan T, n int) <-chan T

DropChan returns a channel on which n values are dropped from the given channel.

func DropChanCtx added in v0.7.0

func DropChanCtx[T any](ctx context.Context, ch <-chan T, n int) <-chan T

DropChanCtx returns a channel on which n values are dropped from the given channel. It stops reading when the context is canceled.

func ElementsMatch added in v0.7.0

func ElementsMatch[T comparable](in ...[]T) bool

ElementsMatch returns true if the given slices contain the same elements.

func ElementsMatchFn added in v0.7.0

func ElementsMatchFn[T any](in [][]T, eq func(T, T) bool) bool

ElementsMatchFn returns true if the given slices contain the same elements, according to the given function.

func Equal

func Equal[T comparable](in ...[]T) bool

Equal returns true if the given slices are equal.

func EqualFn

func EqualFn[T any](in [][]T, eq func(T, T) bool) bool

EqualFn returns true if the given slices are equal, according to the given function.

func Factorial

func Factorial(n int) int

Factorial returns the Factorial of the given number.

func FanIn

func FanIn[T any](chs ...<-chan T) <-chan T

FanIn merges the given channels into a single channel. That is, values are read from each channel in parallel. The returned channel is closed when all the given channels are closed.

func FanInCtx

func FanInCtx[T any](ctx context.Context, chs ...<-chan T) <-chan T

FanInCtx merges the given channels into a single channel. That is, values are read from each channel in parallel. The returned channel is closed when all the given channels are closed or the context is canceled.

func FanOut

func FanOut[T any](ch <-chan T, n int) []<-chan T

FanOut splits the given channel into n channels. The returned channels are closed when the given channel is closed.

func FanOutCtx

func FanOutCtx[T any](ctx context.Context, ch <-chan T, n int) []<-chan T

FanOutCtx splits the given channel into n channels. The returned channels are closed when the given channel is closed or the context is canceled.

func Filter

func Filter[T any](slice []T, fn func(T) bool) []T

Filter returns a slice of the elements in the given slice that satisfy the given predicate.

func FilterIdx

func FilterIdx[T any](slice []T, fn func(int, T) bool) []T

FilterIdx returns a slice of the elements in the given slice that satisfy the given predicate.

func Flatten added in v0.12.0

func Flatten[T any](in [][]T) []T

Flatten returns a slice of the elements in the given slices.

func FlattenChan added in v0.12.0

func FlattenChan[T any](ch <-chan []T) <-chan T

FlattenChan flattens the given channel into a single channel. The returned channel is closed when the given channel is closed.

func FlattenChanCtx added in v0.12.0

func FlattenChanCtx[T any](ctx context.Context, ch <-chan []T) <-chan T

FlattenChanCtx flattens the given channel into a single channel. The returned channel is closed when the given channel is closed or the context is canceled.

func ForChan

func ForChan[T any](ch <-chan T, fn func(T))

ForChan calls the given function for each value in the channel.

func ForChanCtx

func ForChanCtx[T any](ctx context.Context, ch <-chan T, fn func(context.Context, T))

ForChanCtx calls the given function for each value in the channel. It stops iterating when the context is canceled.

func ForEach added in v0.3.0

func ForEach[T any](slice []T, fn func(T))

ForEach calls the given function for each element in the given slice.

func ForEachErr added in v0.3.0

func ForEachErr[T any](slice []T, fn func(T) error) error

ForEachErr calls the given function for each element in the given slice.

func ForEachIdx added in v0.3.0

func ForEachIdx[T any](slice []T, fn func(int, T))

ForEachIdx calls the given function for each index of the given slice.

func ForEachIdxErr added in v0.3.0

func ForEachIdxErr[T any](slice []T, fn func(int, T) error) error

ForEachIdxErr calls the given function for each index of the given slice.

func ForN

func ForN(n int, fn func(int))

ForN calls the given function for each index in the given range.

func ForNErr added in v0.3.0

func ForNErr(n int, fn func(int) error) error

ForNErr calls the given function for each index in the given range.

func ForWindow

func ForWindow[T any](slice []T, size int, fn func([]T))

ForWindow calls the given function for each window of the given size in the given slice.

func ForWindowErr added in v0.3.0

func ForWindowErr[T any](slice []T, size int, fn func([]T) error) error

ForWindowErr calls the given function for each window of the given size in the given slice.

func ForWindowIdx

func ForWindowIdx[T any](slice []T, size int, fn func(int, []T))

ForWindowIdx calls the given function for each window of the given size in the given slice.

func ForWindowIdxErr added in v0.3.0

func ForWindowIdxErr[T any](slice []T, size int, fn func(int, []T) error) error

ForWindowIdxErr calls the given function for each window of the given size in the given slice.

func Forward added in v0.7.0

func Forward[T any](src []<-chan T, dst []chan<- T)

Forward forwards values from the src channel(s) to the dst channel(s).

func ForwardCtx added in v0.7.0

func ForwardCtx[T any](ctx context.Context, src []<-chan T, dst []chan<- T)

ForwardCtx forwards values from the src channel(s) to the dst channel(s). It stops forwarding when the context is canceled.

func GoForEach added in v0.3.0

func GoForEach[T any](ctx context.Context, slice []T, fn func(context.Context, T))

GoForEach calls the given function with each value in the given slice in parallel.

func GoForEachErr added in v0.3.0

func GoForEachErr[T any](ctx context.Context, slice []T, fn func(context.Context, T) error) error

GoForEachErr calls the given function with each value in the given slice in parallel.

func GoForEachIdx added in v0.3.0

func GoForEachIdx[T any](ctx context.Context, slice []T, fn func(context.Context, int, T))

GoForEachIdx calls the given function with each value in the given slice in parallel.

func GoForEachIdxErr added in v0.3.0

func GoForEachIdxErr[T any](ctx context.Context, slice []T, fn func(context.Context, int, T) error) error

GoForEachIdxErr calls the given function with each value in the given slice in parallel.

func GoForN

func GoForN(ctx context.Context, n int, fn func(context.Context, int))

GoForN calls the given function with n unique values in parallel.

func GoForNErr added in v0.3.0

func GoForNErr(ctx context.Context, n int, fn func(context.Context, int) error) error

GoForNErr calls the given function with n unique values in parallel.

func GoForWindow

func GoForWindow[T any](ctx context.Context, slice []T, size int, fn func(context.Context, []T))

GoForWindow calls the given function for each window of the given size in the given slice in parallel.

func GoForWindowErr added in v0.3.0

func GoForWindowErr[T any](ctx context.Context, slice []T, size int, fn func(context.Context, []T) error) error

GoForWindowErr calls the given function for each window of the given size in the given slice in parallel.

func GoForWindowIdx

func GoForWindowIdx[T any](ctx context.Context, slice []T, size int, fn func(context.Context, int, []T))

GoForWindowIdx calls the given function for each window of the given size in the given slice in parallel.

func GoForWindowIdxErr added in v0.3.0

func GoForWindowIdxErr[T any](ctx context.Context, slice []T, size int, fn func(context.Context, int, []T) error) error

GoForWindowIdxErr calls the given function for each window of the given size in the given slice in parallel.

func GoMapChan added in v0.5.0

func GoMapChan[T, R any](ch <-chan T, fn func(T) R) <-chan R

GoMapChan returns a channel that applies the given function to each value in the input channel in parallel.

func GoMapChanCtx added in v0.5.0

func GoMapChanCtx[T, R any](ctx context.Context, ch <-chan T, fn func(context.Context, T) R) <-chan R

GoMapChanCtx returns a channel that applies the given function to each value in the input channel in parallel. It stops iterating when the context is canceled.

func GoMapEach added in v0.3.0

func GoMapEach[T, U any](ctx context.Context, slice []T, fn func(context.Context, T) U) []U

GoMapEach returns a slice of the results of the given function applied to each element in the given slice in parallel.

func GoMapEachErr added in v0.3.0

func GoMapEachErr[T, U any](ctx context.Context, slice []T, fn func(context.Context, T) (U, error)) ([]U, error)

GoMapEachErr returns a slice of the results of the given function applied to each element in the given slice in parallel.

func GoMapEachIdx added in v0.3.0

func GoMapEachIdx[T, U any](ctx context.Context, slice []T, fn func(context.Context, int, T) U) []U

GoMapEachIdx returns a slice of the results of the given function applied to each index of the given slice in parallel.

func GoMapEachIdxErr added in v0.3.0

func GoMapEachIdxErr[T, U any](ctx context.Context, slice []T, fn func(context.Context, int, T) (U, error)) ([]U, error)

GoMapEachIdxErr returns a slice of the results of the given function applied to each index of the given slice in parallel.

func GoMapN

func GoMapN[T any](ctx context.Context, n int, fn func(context.Context, int) T) []T

GoMapN returns a slice of the results of the given function applied in parallel to each index in the given range.

func GoMapNErr added in v0.3.0

func GoMapNErr[T any](ctx context.Context, n int, fn func(context.Context, int) (T, error)) ([]T, error)

GoMapNErr returns a slice of the results of the given function applied in parallel to each index in the given range.

func GoMapWindow

func GoMapWindow[T, U any](ctx context.Context, slice []T, size int, fn func(context.Context, []T) U) []U

GoMapWindow returns a slice of the results of the given function applied to each window of the given size in the given slice in parallel.

func GoMapWindowErr added in v0.3.0

func GoMapWindowErr[T, U any](ctx context.Context, slice []T, size int, fn func(context.Context, []T) (U, error)) ([]U, error)

GoMapWindowErr returns a slice of the results of the given function applied to each window of the given size in the given slice in parallel.

func GoMapWindowIdx

func GoMapWindowIdx[T, U any](ctx context.Context, slice []T, size int, fn func(context.Context, int, []T) U) []U

GoMapWindowIdx returns a slice of the results of the given function applied to each window of the given size in the given slice in parallel.

func GoMapWindowIdxErr added in v0.3.0

func GoMapWindowIdxErr[T, U any](ctx context.Context, slice []T, size int, fn func(context.Context, int, []T) (U, error)) ([]U, error)

GoMapWindowIdxErr returns a slice of the results of the given function applied to each window of the given size in the given slice in parallel.

func Index

func Index[T comparable](in []T, elem T) int

Index returns the index of the given element in the given slice, or -1 if it is not found.

func IndexAll

func IndexAll[T comparable](in []T, elem T) []int

IndexAll returns the indices of all elements that are equal to the given element in the given slice.

func IndexAllFn

func IndexAllFn[T any](in []T, fn func(T) bool) []int

IndexAllFn returns the indices of all elements that satisfy the given function in the given slice.

func IndexFn

func IndexFn[T any](in []T, fn func(T) bool) int

IndexFn returns the index of the first element that satisfies the given function in the given slice, or -1 if it is not found.

func Insert

func Insert[T any](in []T, idx int, elems ...T) []T

Insert returns a slice with the given elements inserted at the given index.

func Intersect

func Intersect[T comparable](in ...[]T) []T

Intersect returns a slice of the elements that are in both the given slices.

func IntersectFn

func IntersectFn[T any](in [][]T, eq func(T, T) bool) []T

IntersectFn returns a slice of the elements that are in both the given slices, according to the given function.

func Last

func Last[T any](in []T) T

Last returns the last element in the given slice.

func Lazy added in v0.3.0

func Lazy[T any](fn func() T) func() T

Lazy is a lazy value. It is initialized once via fn and then cached. It is safe for concurrent use.

func MapChan added in v0.5.0

func MapChan[T, R any](ch <-chan T, fn func(T) R) <-chan R

MapChan returns a channel that applies the given function to each value in the input channel.

func MapChanCtx added in v0.5.0

func MapChanCtx[T, R any](ctx context.Context, ch <-chan T, fn func(context.Context, T) R) <-chan R

MapChanCtx returns a channel that applies the given function to each value in the input channel. It stops iterating when the context is canceled.

func MapEach added in v0.3.0

func MapEach[T, U any](slice []T, fn func(T) U) []U

MapEach returns a slice of the results of the given function applied to each element in the given slice.

func MapEachErr added in v0.3.0

func MapEachErr[T, U any](slice []T, fn func(T) (U, error)) ([]U, error)

MapEachErr returns a slice of the results of the given function applied to each element in the given slice.

func MapEachIdx added in v0.3.0

func MapEachIdx[T, U any](slice []T, fn func(int, T) U) []U

MapEachIdx returns a slice of the results of the given function applied to each index of the given slice.

func MapEachIdxErr added in v0.3.0

func MapEachIdxErr[T, U any](slice []T, fn func(int, T) (U, error)) ([]U, error)

MapEachIdxErr returns a slice of the results of the given function applied to each index of the given slice.

func MapN

func MapN[T any](n int, fn func(int) T) []T

MapN returns a slice of the results of the given function applied to each index in the given range.

func MapNErr added in v0.3.0

func MapNErr[T any](n int, fn func(int) (T, error)) ([]T, error)

MapNErr returns a slice of the results of the given function applied to each index in the given range.

func MapWindow

func MapWindow[T, U any](slice []T, size int, fn func([]T) U) []U

MapWindow returns a slice of the results of the given function applied to each window of the given size in the given slice.

func MapWindowErr added in v0.3.0

func MapWindowErr[T, U any](slice []T, size int, fn func([]T) (U, error)) ([]U, error)

MapWindowErr returns a slice of the results of the given function applied to each window of the given size in the given slice.

func MapWindowIdx

func MapWindowIdx[T, U any](slice []T, size int, fn func(int, []T) U) []U

MapWindowIdx returns a slice of the results of the given function applied to each window of the given size in the given slice.

func MapWindowIdxErr added in v0.3.0

func MapWindowIdxErr[T, U any](slice []T, size int, fn func(int, []T) (U, error)) ([]U, error)

MapWindowIdxErr returns a slice of the results of the given function applied to each window of the given size in the given slice.

func Max

func Max[T constraints.Ordered](in ...T) T

Max returns the maximum value in the given slice.

func MaxFn

func MaxFn[T any](in []T, fn func(T, T) bool) T

MaxFn returns the maximum value in the given slice, according to the given function.

func MaxIdx

func MaxIdx[T constraints.Ordered](in ...T) int

MaxIdx returns the index of the maximum element in the given slice.

func MaxIdxFn

func MaxIdxFn[T any](in []T, fn func(T, T) bool) int

MaxIdxFn returns the index of the maximum element in the given slice, according to the given function.

func Min

func Min[T constraints.Ordered](in ...T) T

Min returns the minimum value in the given slice.

func MinFn

func MinFn[T any](in []T, fn func(T, T) bool) T

MinFn returns the minimum value in the given slice, according to the given function.

func MinIdx

func MinIdx[T constraints.Ordered](in ...T) int

MinIdx returns the index of the minimum element in the given slice.

func MinIdxFn

func MinIdxFn[T any](in []T, fn func(T, T) bool) int

MinIdxFn returns the index of the minimum element in the given slice, according to the given function.

func Must added in v0.7.0

func Must[T any](v T, err error) T

Must returns the given value or panics if the given error is not nil.

func NewBufPipe

func NewBufPipe[T any](size int) (chan<- T, <-chan T)

NewBufPipe returns a pair of connected channels, one for sending and one for receiving. Writes to the in channel block when the buffer is full. The out channel is closed when the in channel is closed.

Example
package main

import (
	"fmt"

	"github.com/go-dj/dj"
)

func main() {
	// Create a new pipe for ints with a buffer of size 3.
	in, out := dj.NewBufPipe[int](3)

	// Write some values to the pipe.
	in <- 1
	in <- 2
	in <- 3

	// The buffer is full, so the write blocks.
	select {
	case in <- 4:
		panic("write should block")

	default:
		// ...
	}

	// Read the values from the pipe.
	fmt.Println(<-out) // 1
	fmt.Println(<-out) // 2
	fmt.Println(<-out) // 3

	// The buffer is empty, so the read blocks.
	select {
	case <-out:
		panic("read should block")

	default:
		// ...
	}

}
Output:

1
2
3

func NewPipe

func NewPipe[T any]() (chan<- T, <-chan T)

NewPipe returns a pair of connected channels, one for sending and one for receiving. Sent values are buffered until they are received. The out channel is closed when the in channel is closed.

Example
package main

import (
	"fmt"

	"github.com/go-dj/dj"
)

func main() {
	// Create a new pipe for ints.
	in, out := dj.NewPipe[int]()

	// Write some values to the pipe.
	// Writes never block; they are buffered until they are read.
	go func() {
		in <- 1
		in <- 2
		in <- 3

		// Close the pipe to signal that no more values will be written.
		// Buffered values can still be read.
		close(in)
	}()

	// Read the values from the pipe.
	for v := range out {
		fmt.Println(v)
	}

}
Output:

1
2
3

func NewPipeline added in v0.5.0

func NewPipeline[In, Out any](ctx context.Context, buf int, fn func(context.Context, In) Result[Out]) (chan<- In, <-chan Result[Out])

NewPipeline returns a pair of connected channels. Values sent to the first channel are processed by fn and the results are sent to the second channel. If buf is greater than or equal to zero, up to buf values are buffered before the pipeline blocks. Otherwise, writes never block.

func None

func None[T any](slice []T, fn func(T) bool) bool

None returns true if the given predicate is false for all elements in the given slice.

func Normal added in v0.3.0

func Normal(mean, stddev float64) float64

Normal returns a random number from a normal distribution with the given mean and standard deviation.

func OnCancel added in v0.12.0

func OnCancel(ctx context.Context, fn func())

OnCancel registers a function to be called when the given context is cancelled.

func Perms

func Perms[T any](in []T) [][]T

Perms returns a slice of all the possible permutations of the given slice.

func PermsIdx

func PermsIdx(n int) [][]int

PermsIdx returns a slice containing the indices of all the possible permutations of a slice of the given length.

func PickUniform added in v0.9.0

func PickUniform[T any](slice ...T) T

PickUniform returns an element from the given slice, chosen uniformly at random.

func PickWeighted added in v0.10.0

func PickWeighted[T any](slice []T, weights []int) T

PickWeighted returns an element from the given slice, chosen at random according to the given weights.

func Pointer

func Pointer[T any](v T) *T

Pointer returns a pointer to the given value.

func Power

func Power[T any](in []T) [][]T

Power returns a slice of all the possible combinations of the given slice.

func PowerIdx

func PowerIdx(n int) [][]int

PowerIdx returns a slice containing the indices of all the possible combinations of a slice of the given length.

func Range

func Range(start, end int) []int

Range returns a slice of integers from start to end-1.

func RangeN

func RangeN(n int) []int

RangeN returns a slice of integers from 0 to n-1.

func RecvFrom added in v0.5.0

func RecvFrom[T any](chs ...<-chan T) (T, bool)

RecvFrom receives a value from one of the given channels. It blocks until a value is received, which it returns. The boolean indicates whether the read was successful; it is false if the channel is closed.

func RecvFromCtx added in v0.5.0

func RecvFromCtx[T any](ctx context.Context, chs ...<-chan T) (T, bool)

RecvFromCtx receives a value from one of the given channels. It blocks until a value is received, which it returns, or the context is canceled. The boolean indicates whether the read was successful; it is false if the channel is closed.

func Reduce

func Reduce[T, U any](slice []T, init U, fn func(U, T) U) U

Reduce returns the result of applying the given function to each element in the given slice, starting with the given initial value.

func ReduceIdx

func ReduceIdx[T, U any](slice []T, init U, fn func(U, int) U) U

ReduceIdx returns the result of applying the given function to each index of the given slice, starting with the given initial value.

func Remove

func Remove[T comparable](in []T, elems ...T) []T

Remove returns a slice with the given elements removed.

func RemoveFn

func RemoveFn[T any](in []T, fn func(T) bool) []T

RemoveFn returns a slice with the elements that satisfy the given function removed.

func RemoveIdx

func RemoveIdx[T any](in []T, indices ...int) []T

RemoveIdx returns a slice with the elements at the given indices removed.

func RemoveN

func RemoveN[T any](in []T, idx, n int) []T

RemoveN returns a slice with n elements removed at the given index.

func RemoveRange

func RemoveRange[T any](in []T, start, end int) []T

RemoveRange returns a slice with the elements in the given range removed.

func RepeatN added in v0.9.0

func RepeatN[T any](n int, value T) []T

RepeatN returns a slice of n copies of the given value.

func Reverse

func Reverse[T any](in []T) []T

Reverse returns a reversed slice of the given slice.

func Same

func Same[T comparable](in ...T) bool

Same returns true if all the given values are equal.

func SameFn

func SameFn[T any](in []T, fn func(T, T) bool) bool

SameFn returns true if all the given values are equal, according to the given function.

func SendTo added in v0.5.0

func SendTo[T any](v T, chs ...chan<- T)

SendTo sends the given value to one of the given channels. It blocks until the value is sent.

func SendToCtx added in v0.5.0

func SendToCtx[T any](ctx context.Context, v T, chs ...chan<- T)

SendToCtx sends the given value to one of the given channels. It blocks until the value is sent or the context is canceled.

func Set

func Set[T comparable](in []T) map[T]struct{}

SetFn returns a map set of the elements in the given slice, with duplicates removed.

func Shuffle

func Shuffle[T any](in []T) []T

Shuffle returns a shuffled slice of the given slice.

func Sort

func Sort[T constraints.Ordered](in []T) []T

Sort returns a sorted slice of the given slice.

func SortFn

func SortFn[T any](in []T, fn func(T, T) bool) []T

SortFn returns a sorted slice of the given slice, according to the given function.

func Sum

func Sum[T constraints.Ordered](in []T) T

Sum returns the sum of the given slice.

func TakeChan

func TakeChan[T any](ch <-chan T, n int) <-chan T

TakeChan returns a channel on which n values are taken from the given channel.

func TakeChanCtx

func TakeChanCtx[T any](ctx context.Context, ch <-chan T, n int) <-chan T

TakeChanCtx returns a channel on which n values are taken from the given channel. It stops reading when the context is canceled.

func Uniform added in v0.3.0

func Uniform(min, max float64) float64

Uniform returns a random number from a uniform distribution between the given min and max values.

func Uniq

func Uniq[T comparable](in []T) []T

Uniq returns a slice of the unique elements in the given slice.

func UniqFn

func UniqFn[T any](in []T, eq func(T, T) bool) []T

UniqFn returns a slice of the unique elements in the given slice, according to the given function.

func Unzip

func Unzip[T any](in [][]T) [][]T

Unzip returns a slice of slices, where each slice contains the elements at the same index in the given tuples.

func Weighted added in v0.10.0

func Weighted(weights []int) int

Weighted returns a random index from the given weights.

func WithParallelism added in v0.3.0

func WithParallelism(ctx context.Context, n int) context.Context

WithParallelism returns a context with the given parallelism. Certain functions in this package will use this value to determine how many goroutines to run concurrently. If the context already has a parallelism value, it will be overwritten. If not set, the default parallelism is the number of CPUs.

func Zero

func Zero[T any]() T

Zero returns the Zero value of the given type.

func Zip

func Zip[T any](in ...[]T) [][]T

Zip returns a slice of tuples, where each tuple contains the elements at the same index in the given slices.

func ZipChan

func ZipChan[T any](chs ...<-chan T) <-chan []T

ZipChan zips the given channels into a single channel. The returned channel is closed when all the given channels are closed.

func ZipChanCtx

func ZipChanCtx[T any](ctx context.Context, chs ...<-chan T) <-chan []T

ZipChanCtx zips the given channels into a single channel. The returned channel is closed when all the given channels are closed or the context is canceled.

Types

type ChunkCond added in v0.13.0

type ChunkCond[T any] struct {
	Limit int
	Cond  func([]T) int
}

ChunkCond is a condition for chunking a slice.

type Future added in v0.3.0

type Future[T any] struct {
	// contains filtered or unexported fields
}

Future represents a value that will be available in the future. Its value is not available until the future is resolved, at which point it can be retrieved using Get.

func NewFuture added in v0.7.0

func NewFuture[T any](resolver func() Result[T]) *Future[T]

NewFuture creates a new Future.

func Then added in v0.7.0

func Then[T, U any](future *Future[T], resolver func(T) Result[U]) *Future[U]

Then returns a new Future that is resolved when the current Future is resolved. The resolver function is called with the value of the current Future. If the current Future is resolved with an error, the resolver function is not called and the returned Future is resolved with the same error.

func (*Future[T]) Get added in v0.3.0

func (f *Future[T]) Get() Result[T]

Get returns the result of the future. It blocks until the value has been set.

type Gate added in v0.9.0

type Gate struct {
	// contains filtered or unexported fields
}

Gate is a type that can block and unblock execution. The gate can be opened with Open() and closed with Close(). Calling Wait() will block until the gate is opened. If the gate is already open, Wait() will return immediately.

func NewGate added in v0.9.0

func NewGate() *Gate

NewGate returns a new gate.

func (*Gate) Close added in v0.9.0

func (g *Gate) Close()

Close closes the gate. If the gate is already closed, this is a no-op.

func (*Gate) Open added in v0.9.0

func (g *Gate) Open()

Open opens the gate. If the gate is already open, this is a no-op.

func (*Gate) Wait added in v0.9.0

func (g *Gate) Wait()

Wait blocks until the gate is opened. If the gate is already open, this is a no-op.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group is a group of goroutines.

func NewGroup

func NewGroup(ctx context.Context, weight int) *Group

NewGroup returns a new group of goroutines. The given context is used to cancel all goroutines in the group. The number of goroutines permitted to run concurrently is given by n.

func (*Group) Cancel added in v0.3.0

func (s *Group) Cancel()

Cancel cancels all goroutines in the group. This is destructive and cannot be undone; the group cannot be reused.

func (*Group) Child added in v0.3.0

func (s *Group) Child() *Group

Child returns a sub group inside the group.

func (*Group) Go

func (s *Group) Go(weight int, fn func(context.Context))

Go runs the given function in the group.

func (*Group) GoN

func (s *Group) GoN(n int, weight int, fn func(context.Context, int)) *Group

GoN runs the given function n times concurrently in a child group and returns the child group.

func (*Group) Parent added in v0.3.0

func (s *Group) Parent() *Group

Parent returns the parent group, if any.

func (*Group) Wait

func (s *Group) Wait()

Wait waits for all goroutines in the group to finish.

type Iter

type Iter[T any] interface {
	Readable[T]

	// Collect returns a slice containing all the values in the iterator.
	Collect() []T

	// Take returns a new iterator that will return at most n values from the original iterator.
	Take(n int) Iter[T]

	// Drop returns a new iterator that will drop the first n values from the original iterator.
	Drop(n int) Iter[T]

	// Filter returns a new iterator that will only return values for which the given predicate returns true.
	Filter(fn func(T) bool) Iter[T]

	// Chan returns a channel that will receive all the values in the iterator.
	Chan() <-chan T
}

Iter is a type that can be read sequentially.

func ChanIter

func ChanIter[T any](ch <-chan T) Iter[T]

ChanIter returns an iterator over the given channel.

func ChanIterCtx

func ChanIterCtx[T any](ctx context.Context, ch <-chan T) Iter[T]

ChanIterCtx returns an iterator over the given channel, which will be closed when the given context is canceled.

func ChunkIter

func ChunkIter[T any](iter Iter[T], size int) Iter[[]T]

ChunkIter returns an iterator over the given iterator, chunking the values into slices of the given size.

func FlattenIter

func FlattenIter[T any](iter Iter[Iter[T]]) Iter[T]

FlattenIter returns an iterator over the given iterator, flattening nested iterators. That is, it converts an iterator over iterators into an iterator over the values of those iterators.

func FuncIter

func FuncIter[T any](fn func() (T, bool)) Iter[T]

FuncIter returns an iterator over the given function.

func JoinIter

func JoinIter[T any](iters ...Iter[T]) Iter[T]

JoinIter concatenates the given iterators into a single iterator.

func MapIter

func MapIter[T, U any](iter Iter[T], fn func(T) U) Iter[U]

MapIter applies the given function to each value returned by the given iterator.

func NewIter

func NewIter[T any](r Readable[T]) Iter[T]

NewIter returns a new Iter that reads from the given Readable.

func SliceIter

func SliceIter[T any](slice []T) Iter[T]

SliceIter returns an iterator over the given slice.

func ZipIter

func ZipIter[T any](iters ...Iter[T]) Iter[[]T]

ZipIter returns an iterator over the given iterators, zipping the values together. That is, it converts an iterator over iterators into an iterator over tuples of the values of those iterators.

type Job

type Job[Req, Res any] struct {
	// contains filtered or unexported fields
}

Job is a Job that has been submitted to a worker pool.

func (*Job[Req, Res]) Await added in v0.9.0

func (job *Job[Req, Res]) Await() Result[Res]

Await returns the result of the job, blocking until the job has finished. If the job failed, the error is returned.

type Map

type Map[Key comparable, Value any] struct {
	// contains filtered or unexported fields
}

func NewMap added in v0.3.0

func NewMap[Key comparable, Value any]() *Map[Key, Value]

func (*Map[Key, Value]) Delete added in v0.3.0

func (m *Map[Key, Value]) Delete(key Key)

func (*Map[Key, Value]) Get added in v0.3.0

func (m *Map[Key, Value]) Get(key Key) (Value, bool)

func (*Map[Key, Value]) Items added in v0.3.0

func (m *Map[Key, Value]) Items() map[Key]Value

func (*Map[Key, Value]) Len added in v0.3.0

func (m *Map[Key, Value]) Len() int

func (*Map[Key, Value]) Set added in v0.3.0

func (m *Map[Key, Value]) Set(key Key, value Value)

type MinMaxCounter added in v0.9.0

type MinMaxCounter struct {
	// contains filtered or unexported fields
}

MinMaxCounter is a thread-safe counter which records the minimum and maximum values it has reached.

func (*MinMaxCounter) Add added in v0.9.0

func (c *MinMaxCounter) Add(v int)

Add adds the given value to the counter.

func (*MinMaxCounter) Current added in v0.9.0

func (c *MinMaxCounter) Current() int

Current returns the current value of the counter.

func (*MinMaxCounter) Max added in v0.9.0

func (c *MinMaxCounter) Max() int

Max returns the maximum value the counter has reached.

func (*MinMaxCounter) Min added in v0.9.0

func (c *MinMaxCounter) Min() int

Min returns the minimum value the counter has reached.

type Peeker

type Peeker[T any] interface {
	Iter[T]

	// Peek returns the next value in the iterator without advancing it.
	Peek() (T, bool)
}

Peeker is a peekable iterator.

func WithPeek

func WithPeek[T any](iter Iter[T]) Peeker[T]

WithPeek wraps the given iterator with a peekable iterator.

type Pool added in v0.7.0

type Pool[Req, Res any] struct {
	// contains filtered or unexported fields
}

Pool is a pool of workers that can be used to process work concurrently. Jobs of type Req are submitted to the pool and are processed by a worker. The result of the job is returned as a value of type Res.

func NewPool added in v0.7.0

func NewPool[Req, Res any](ctx context.Context, weight int, fn func(context.Context, Req) Result[Res]) *Pool[Req, Res]

NewPool returns a new worker pool which handles jobs of type Req up to the given weight. The given function is called for each job submitted to the pool, returning a Result[Res].

Example
package main

import (
	"context"
	"fmt"
	"strconv"

	"github.com/go-dj/dj"
)

func main() {
	// Create a pool of weight 2.
	pool := dj.NewPool(context.Background(), 2, func(_ context.Context, in string) dj.Result[int] {
		return dj.NewResult(strconv.Atoi(in))
	})
	defer pool.Close()

	// Submit 3 jobs to the pool.
	job1 := pool.Submit(context.Background(), 1, "1")
	job2 := pool.Submit(context.Background(), 1, "foo")
	job3 := pool.Submit(context.Background(), 1, "3")

	// Each job should be processed.
	fmt.Println(job1.Await().Unpack())
	fmt.Println(job2.Await().Unpack())
	fmt.Println(job3.Await().Unpack())

	// Submit a list of jobs to the pool.
	fmt.Println(pool.Process(context.Background(), 1, "4", "5", "6"))

	// If any job fails, the entire list of jobs will fail.
	fmt.Println(pool.Process(context.Background(), 1, "7", "foo", "9"))

}
Output:

1 <nil>
0 strconv.Atoi: parsing "foo": invalid syntax
3 <nil>
[4 5 6] <nil>
[] strconv.Atoi: parsing "foo": invalid syntax

func (*Pool[Req, Res]) Close added in v0.8.0

func (p *Pool[Req, Res]) Close()

Close closes the pool. Subsequent calls to Submit will panic.

func (*Pool[Req, Res]) Process added in v0.7.0

func (p *Pool[Req, Res]) Process(ctx context.Context, weight int, reqs ...Req) ([]Res, error)

Process is a convenience function that submits the given jobs to the pool and returns the results. The results are returned in the same order as the jobs were submitted. If any of the jobs fail, the error is returned immediately.

func (*Pool[Req, Res]) Submit added in v0.7.0

func (p *Pool[Req, Res]) Submit(ctx context.Context, weight int, req Req) *Job[Req, Res]

Submit submits the given job to the pool.

type Queue added in v0.3.0

type Queue[T any] struct {
	// contains filtered or unexported fields
}

func (*Queue[T]) First added in v0.15.0

func (q *Queue[T]) First() T

func (*Queue[T]) Items added in v0.3.0

func (q *Queue[T]) Items() []T

func (*Queue[T]) Last added in v0.15.0

func (q *Queue[T]) Last() T

func (*Queue[T]) Len added in v0.3.0

func (q *Queue[T]) Len() int

func (*Queue[T]) PopBack added in v0.3.0

func (q *Queue[T]) PopBack() (T, bool)

func (*Queue[T]) PopFront added in v0.3.0

func (q *Queue[T]) PopFront() (T, bool)

func (*Queue[T]) PushBack added in v0.3.0

func (q *Queue[T]) PushBack(v ...T)

func (*Queue[T]) PushFront added in v0.3.0

func (q *Queue[T]) PushFront(items ...T)

type Readable added in v0.3.0

type Readable[T any] interface {
	// Read returns the next value in the iterator.
	// If the iterator is exhausted, the boolean will be false.
	Read() (T, bool)
}

Readable is a type that can be iterated over by repeatedly calling Read.

type Result added in v0.5.0

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result is a type that represents a value or an error.

func Err added in v0.5.0

func Err[T any](err error) Result[T]

Err returns a new Result with the given error and no value.

func NewResult added in v0.5.0

func NewResult[T any](val T, err error) Result[T]

NewResult returns a new Result with the given value and error.

func Ok added in v0.5.0

func Ok[T any](val T) Result[T]

Ok returns a new Result with the given value and no error.

func (Result[T]) Err added in v0.7.0

func (r Result[T]) Err() error

Err returns the error of the Result. If the Result is a value, the error is nil.

func (Result[T]) String added in v0.7.0

func (r Result[T]) String() string

String returns a string representation of the Result.

func (Result[T]) Unpack added in v0.7.0

func (r Result[T]) Unpack() (T, error)

Unpack returns the value and error of the Result.

func (Result[T]) Val added in v0.7.0

func (r Result[T]) Val() T

Val returns the value of the Result. If the Result is an error, this panics.

type Semaphore added in v0.12.0

type Semaphore struct {
	// contains filtered or unexported fields
}

Semaphore is a weighted semaphore.

func NewSemaphore added in v0.12.0

func NewSemaphore(max int) *Semaphore

NewSemaphore returns a new weighted semaphore.

func (*Semaphore) Acquire added in v0.12.0

func (s *Semaphore) Acquire(ctx context.Context, n int) error

Acquire acquires n resources. If the context is canceled, the acquisition is aborted and an error is returned.

func (*Semaphore) Release added in v0.12.0

func (s *Semaphore) Release(n int)

Release releases n resources.

func (*Semaphore) Wait added in v0.12.0

func (s *Semaphore) Wait()

Wait waits for all resources to be released.

type Singular added in v0.3.0

type Singular[T any] struct {
	// contains filtered or unexported fields
}

Singular obtains a value exactly once. Any subsequent attempts to set the value will be ignored.

func (*Singular[T]) Get added in v0.3.0

func (s *Singular[T]) Get() T

Get returns the value if it has been set.

func (*Singular[T]) Set added in v0.3.0

func (s *Singular[T]) Set(val T)

Set sets the value if it has not already been set.

type Waiter added in v0.14.0

type Waiter struct {
	// contains filtered or unexported fields
}

Waiter allows goroutines to wait for a signal. When Signal() is called, all goroutines waiting on Wait() will be unblocked. Subsequent calls to Wait() will block again.

func NewWaiter added in v0.14.0

func NewWaiter() *Waiter

NewWaiter returns a new Waiter.

func (*Waiter) Signal added in v0.14.0

func (w *Waiter) Signal()

Signal unblocks all goroutines waiting on Wait().

func (*Waiter) Wait added in v0.14.0

func (w *Waiter) Wait()

Wait blocks until Signal() is called.

type Writable

type Writable[T any] interface {
	Write(T) error
}

Writable is a type that can be written to by repeatedly calling Write.

type Writer

type Writer[T any] interface {
	Writable[T]
}

Writer is a type that can be written to by repeatedly calling Write.

func ChanWriter

func ChanWriter[T any](ch chan<- T) Writer[T]

ChanWriter returns a writer that writes to the given channel.

func ChanWriterCtx

func ChanWriterCtx[T any](ctx context.Context, ch chan<- T) Writer[T]

ChanWriterCtx returns a writer that writes to the given channel until the given context is canceled.

func FuncWriter

func FuncWriter[T any](fn func(T) error) Writer[T]

FuncWriter returns a writer that calls the given function for each value to be written.

func NewWriter

func NewWriter[T any](w Writable[T]) Writer[T]

NewWriter returns a new Writer that writes to the given Writable.

Jump to

Keyboard shortcuts

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