stream

package module
v0.0.0-...-870cbdc Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2024 License: MIT Imports: 7 Imported by: 0

README

stream

streams package for Go.

docs

Quick Examples

Stream a slice
func ExampleFromSlice() {
	var (
		filterCalled    bool
		transformCalled bool
	)

	stream := FromSlice([]int{3, 8, 11, 24, 37, 42}).
		Filter(func(elem int) bool { filterCalled = true; return elem >= 10 }).
		Skip(1).
		Limit(2).
		Transform(func(elem int) int { transformCalled = true; return elem * 2 })

	fmt.Println(filterCalled)         // NOTE: false is printed here - streams are lazily evaluated
	fmt.Println(transformCalled)      // NOTE: false is printed here - streams are lazily evaluated
	fmt.Println(stream.First().Get()) // NOTE: the stream has now been consumed
	fmt.Println(stream.FirstWhere(func(i int) bool { return i%2 == 1 }).Get())
	fmt.Println(filterCalled)
	fmt.Println(transformCalled)

	// Output:
	// false
	// false
	// 48 true
	// 0 false
	// true
	// true
}
Stream a channel
func ExampleFromChan() {
	var (
		filterCalled    bool
		transformCalled bool
	)

	ch := make(chan int)
	go func() {
		defer close(ch)
		ch <- 3
		ch <- 8
		ch <- 11
		ch <- 24
		ch <- 37
		ch <- 42
	}()

	stream := FromChan(ch).
		Filter(func(elem int) bool { filterCalled = true; return elem >= 10 }).
		Skip(1).
		Limit(2).
		Transform(func(elem int) int { transformCalled = true; return elem * 2 })

	fmt.Println(filterCalled)    // NOTE: false is printed here - streams are lazily evaluated
	fmt.Println(transformCalled) // NOTE: false is printed here - streams are lazily evaluated
	fmt.Println(stream.First().Get())
	fmt.Println(stream.FirstWhere(func(i int) bool { return i%2 == 1 }).Get())
	fmt.Println(stream.First().Get())
	fmt.Println(filterCalled)
	fmt.Println(transformCalled)

	// Output:
	// false
	// false
	// 48 true
	// 0 false
	// 0 false
	// true
	// true
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func And

func And[T ~bool](cumulative, next T) T

func Append

func Append[T any, S ~[]T](total, next S) S

func ApplyLeft

func ApplyLeft[Left, Right, Out any, Func ~func(Left, Right) Out](f Func, left Left) func(Right) Out

ApplyLeft takes a binary function (Left, Right) -> Out, and a value for it's left argument, then returns a unary function Right -> Out.

Example
package main

import (
	"fmt"

	"github.com/dabbertorres/stream"
)

func main() {
	concat := func(prefix, suffix string) string {
		return prefix + " " + suffix
	}

	commonPrefix := stream.ApplyLeft(concat, "INFO:")

	fmt.Println(commonPrefix("it worked!"))

}
Output:

INFO: it worked!

func ApplyRight

func ApplyRight[Left, Right, Out any, Func ~func(Left, Right) Out](f Func, right Right) func(Left) Out

ApplyRight takes a binary function, (Left, Right) -> Out, and a value for it's right argument, then returns a unary function Left -> Out.

Example
package main

import (
	"fmt"

	"github.com/dabbertorres/stream"
)

type Foo struct {
	X int
}

func (f Foo) Add(y int) int { return f.X + y }

func main() {
	f := stream.ApplyRight(Foo.Add, 5)
	result := f(Foo{X: 3})
	fmt.Println(result)

}
Output:

8

func Associate

func Associate[K comparable, V any, In any](in Stream[In], f func(In) (K, V)) map[K]V

func AssociateBy

func AssociateBy[K comparable, V any, In any](f func(In) (K, V)) func(Stream[In]) map[K]V

func AssociateByKeyValue

func AssociateByKeyValue[K comparable, V any](in Stream[KeyValue[K, V]]) map[K]V

func AssociateKeyValue

func AssociateKeyValue[K comparable, V any](kv KeyValue[K, V]) (K, V)

AssociateKeyValue provides a default function for [KeyValue]s for Associate.

func BitAnd

func BitAnd[T Integer](cumulative, next T) T

func BitClear

func BitClear[T Integer](cumulative, next T) T

func BitOr

func BitOr[T Integer](cumulative, next T) T

func BitXor

func BitXor[T Integer](cumulative, next T) T

func Chain

func Chain[Out, Mid, In any, First ~func(In) Mid, Second ~func(Mid) Out](first First, second Second) func(In) Out

Chain creates a unary function In -> Out from two functions such that In -> Mid -> Out.

Example
package main

import (
	"fmt"

	"github.com/dabbertorres/stream"
)

func main() {
	var (
		isPositive = func(x int) bool { return x > 0 }
		isEven     = func(x int) bool { return x%2 == 0 }
		doubleIt   = func(x int) int { return x * 2 }
	)

	bizLogic := stream.Chain(
		stream.Chain(
			stream.ApplyRight(stream.Stream[int].Filter, isPositive),
			stream.ApplyRight(stream.Stream[int].Filter, isEven),
		),
		stream.ApplyRight(stream.Stream[int].Transform, doubleIt),
	)

	bizLogic(stream.FromSlice([]int{-3, 4, 1, 12})).
		ForEach(func(i int) { fmt.Println(i) })

}
Output:

8
24

func Difference

func Difference[T Number](cumulative, next T) T

func FilterBy

func FilterBy[T any](filter func(T) bool) func(Stream[T]) Stream[T]

func FlatMapBy

func FlatMapBy[In, Out any](mapper func(In) Stream[Out]) func(Stream[In]) Stream[Out]

func Identity

func Identity[T comparable](v T) T

func KeyValueLess

func KeyValueLess[K Ordered, V any](lhs, rhs KeyValue[K, V]) bool

KeyValueLess provides a generic LessFunc for [KeyValue]s with an Ordered key.

func LeftShift

func LeftShift[T Integer](cumulative, next T) T

func MapBy

func MapBy[In, Out any](mapper func(In) Out) func(Stream[In]) Stream[Out]

func Or

func Or[T ~bool](cumulative, next T) T

func OrderedLess

func OrderedLess[T Ordered](lhs, rhs T) bool

OrderedLess provides a generic LessFunc for builtin types that are Ordered.

func Pipe

func Pipe[Out, Mid, In any, First ~func(In) Mid, Second ~func(Mid) Out](in In, first First, second Second) Out

Pipe applies in to first, passes its result to second, and returns second's result.

Example

ExamplePipe is the same logic as [ExampleChain], but shows the readability improvement of Pipe in certain cases.

package main

import (
	"fmt"

	"github.com/dabbertorres/stream"
)

func main() {
	var (
		isPositive = func(x int) bool { return x > 0 }
		isEven     = func(x int) bool { return x%2 == 0 }
		doubleIt   = func(x int) int { return x * 2 }
	)

	stream.Pipe(
		stream.FromSlice([]int{-3, 4, 1, 12}),
		stream.Chain(
			stream.ApplyRight(stream.Stream[int].Filter, isPositive),
			stream.ApplyRight(stream.Stream[int].Filter, isEven),
		),
		stream.ApplyRight(stream.Stream[int].Transform, doubleIt),
	).ForEach(func(i int) { fmt.Println(i) })

}
Output:

8
24

func Product

func Product[T Number](cumulative, next T) T

func Quotient

func Quotient[T Number](cumulative, next T) T

func Remainder

func Remainder[T Integer](cumulative, next T) T

func RightShift

func RightShift[T Integer](cumulative, next T) T

func SortedBy

func SortedBy[T any](less LessFunc[T]) func(Stream[T]) Stream[T]

func Sum

func Sum[T Number | ~string](cumulative, next T) T

func TransformBy

func TransformBy[T any](transform func(T) T) func(Stream[T]) Stream[T]

func ValueMapper

func ValueMapper[K comparable, InV, OutV any](f func(InV) OutV) func(KeyValue[K, InV]) KeyValue[K, OutV]

ValueMapper is a helper wrapper to simplify mapping only the value of a KeyValue.

func ValueTransform

func ValueTransform[K comparable, V any](f func(V) V) func(KeyValue[K, V]) KeyValue[K, V]

ValueTransform is a helper wrapper to simplify transforming only the value of a KeyValue.

Types

type Associater

type Associater[In any, K comparable, V any] struct {
	// contains filtered or unexported fields
}

func (Associater[In, K, V]) By

func (a Associater[In, K, V]) By(f func(In) (K, V)) map[K]V

func (Associater[In, K, V]) ByTo

func (a Associater[In, K, V]) ByTo(to map[K]V, f func(In) (K, V))

type Decoder

type Decoder interface {
	Decode(any) error
}

Decoder is implemented by most of the encoding/* packages in the standard library, and often by third-party packages providing similar capabilities.

type Float

type Float interface {
	~float32 | ~float64
}

type Integer

type Integer interface {
	Signed | Unsigned
}

type KeyValue

type KeyValue[K comparable, V any] struct {
	Key K
	Val V
}

type KeyValueAssociater

type KeyValueAssociater[K comparable, V any] struct {
	// contains filtered or unexported fields
}

KeyValueAssociater is a helper to reduce noise when using Associate with [KeyValue]s.

func AssociateFromKeyValue

func AssociateFromKeyValue[K comparable, V any](in Stream[KeyValue[K, V]]) KeyValueAssociater[K, V]

func (KeyValueAssociater[K, V]) By

func (a KeyValueAssociater[K, V]) By(f func(K, V) (K, V)) map[K]V

By creates a map[K]V from the Stream, with keys and values defined by f. If f is nil, the identity function is used (K and V without any changes).

func (KeyValueAssociater[K, V]) ByTo

func (a KeyValueAssociater[K, V]) ByTo(to map[K]V, f func(K, V) (K, V))

ByTo fills to from the Stream, with keys and values defined by f. If f is nil, the identity function is used (K and V without any changes).

type LessFunc

type LessFunc[T any] func(lhs, rhs T) bool

LessFunc is a function that returns true when lhs is less than rhs.

type MinMax

type MinMax[T any] struct {
	Min T
	Max T
}

type Number

type Number interface {
	Integer | Float
}

type Optional

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

func None

func None[T any]() Optional[T]

func OptionalFromPointer

func OptionalFromPointer[T any](ptr *T) Optional[T]

func Some

func Some[T any](value T) Optional[T]

func (Optional[T]) Get

func (o Optional[T]) Get() (T, bool)

func (Optional[T]) GetOrDefault

func (o Optional[T]) GetOrDefault(defaultVal T) T

func (Optional[T]) GetOrDefaultFunc

func (o Optional[T]) GetOrDefaultFunc(defaultFunc func() T) T

func (Optional[T]) IfNone

func (o Optional[T]) IfNone(f func())

func (Optional[T]) IfSome

func (o Optional[T]) IfSome(f func(T))

func (Optional[T]) MarshalJSON

func (o Optional[T]) MarshalJSON() ([]byte, error)

func (Optional[T]) MustGet

func (o Optional[T]) MustGet() T

func (Optional[T]) None

func (o Optional[T]) None() bool

func (Optional[T]) Some

func (o Optional[T]) Some() bool

func (*Optional[T]) UnmarshalJSON

func (o *Optional[T]) UnmarshalJSON(data []byte) error

type Ordered

type Ordered interface {
	Number | ~string
}

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Stream

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

func ApplyTo

func ApplyTo[T any, Func ~func(Stream[T]) Stream[T]](in Stream[T], f Func) Stream[T]

func Filter

func Filter[T any](in Stream[T], filter func(T) bool) Stream[T]

func FlatMap

func FlatMap[In, Out any](in Stream[In], mapper func(In) Stream[Out]) Stream[Out]

func Flatten

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

func FromChan

func FromChan[T any](src <-chan T) Stream[T]
Example
var (
	filterCalled    bool
	transformCalled bool
)

ch := make(chan int)
go func() {
	defer close(ch)
	ch <- 3
	ch <- 8
	ch <- 11
	ch <- 24
	ch <- 37
	ch <- 42
}()

stream := FromChan(ch).
	Filter(func(elem int) bool { filterCalled = true; return elem >= 10 }).
	Skip(1).
	Limit(2).
	Transform(func(elem int) int { transformCalled = true; return elem * 2 })

fmt.Println(filterCalled)    // NOTE: false is printed here - streams are lazily evaluated
fmt.Println(transformCalled) // NOTE: false is printed here - streams are lazily evaluated
fmt.Println(stream.First().Get())
fmt.Println(stream.FirstWhere(func(i int) bool { return i%2 == 1 }).Get())
fmt.Println(stream.First().Get())
fmt.Println(filterCalled)
fmt.Println(transformCalled)
Output:

false
false
48 true
0 false
0 false
true
true

func FromDecoder

func FromDecoder[T any](dec Decoder, onError func(error)) Stream[T]

FromDecoder reads T values from the given Decoder until an error is encountered, which results in the end of the Stream. If the error is not io.EOF, onError is called with the error. onError may be nil, in which case the error is silently dropped.

Example
type bar struct {
	Foo int `json:"foo"`
}

data := []byte(`
    {"foo": 7}
    {"foo": 5}
    {"foo": 7}
    {"foo": -13}
`)

results := FromDecoder[bar](json.NewDecoder(bytes.NewReader(data)), nil).
	Distinct().
	Filter(func(b bar) bool { return b.Foo >= 0 }).
	Collect()

fmt.Println(results)
Output:

[{7} {5}]

func FromFunc

func FromFunc[T any](f func() Optional[T]) Stream[T]
Example
var transformCalled bool

i := 1
stream := FromFunc(func() Optional[int] {
	v := i
	i *= 2
	if v <= 64 {
		return Some(v)
	}
	return None[int]()
}).Skip(1).
	Limit(10).
	Transform(func(elem int) int { transformCalled = true; return elem * 3 })

fmt.Println(transformCalled) // NOTE: false is printed here - streams are lazily evaluated
fmt.Println(stream.Collect())
fmt.Println(transformCalled)
Output:

false
[6 12 24 48 96 192]
true

func FromMap

func FromMap[K comparable, V any, M ~map[K]V](src M) Stream[KeyValue[K, V]]

func FromOptional

func FromOptional[T any](opt Optional[T]) Stream[T]

func FromSlice

func FromSlice[T any, S ~[]T](src S) Stream[T]
Example
var (
	filterCalled    bool
	transformCalled bool
)

stream := FromSlice([]int{3, 8, 11, 24, 37, 42}).
	Filter(func(elem int) bool { filterCalled = true; return elem >= 10 }).
	Skip(1).
	Limit(2).
	Transform(func(elem int) int { transformCalled = true; return elem * 2 })

fmt.Println(filterCalled)         // NOTE: false is printed here - streams are lazily evaluated
fmt.Println(transformCalled)      // NOTE: false is printed here - streams are lazily evaluated
fmt.Println(stream.First().Get()) // NOTE: the stream has now been consumed
fmt.Println(stream.FirstWhere(func(i int) bool { return i%2 == 1 }).Get())
fmt.Println(filterCalled)
fmt.Println(transformCalled)
Output:

false
false
48 true
0 false
true
true

func Join

func Join[T any](streams ...Stream[T]) Stream[T]

func Map

func Map[In, Out any](in Stream[In], mapper func(In) Out) Stream[Out]

func Sorted

func Sorted[T any](in Stream[T], less LessFunc[T]) Stream[T]

func Transform

func Transform[T any](in Stream[T], transform func(T) T) Stream[T]

func (Stream[T]) All

func (s Stream[T]) All(f func(T) bool) (allMatched bool)

func (Stream[T]) Any

func (s Stream[T]) Any(f func(T) bool) (anyMatched bool)

func (Stream[T]) Append

func (s Stream[T]) Append(out []T) []T

func (Stream[T]) Collect

func (s Stream[T]) Collect() (out []T)

func (Stream[T]) Distinct

func (s Stream[T]) Distinct() Stream[T]

func (Stream[T]) DropWhile

func (s Stream[T]) DropWhile(f func(T) bool) Stream[T]

func (Stream[T]) Filter

func (s Stream[T]) Filter(filter func(T) bool) Stream[T]

func (Stream[T]) First

func (s Stream[T]) First() (opt Optional[T])

func (Stream[T]) FirstWhere

func (s Stream[T]) FirstWhere(f func(T) bool) (opt Optional[T])

func (Stream[T]) ForEach

func (s Stream[T]) ForEach(f func(T))

func (Stream[T]) Limit

func (s Stream[T]) Limit(n int) Stream[T]

func (Stream[T]) Max

func (s Stream[T]) Max(less LessFunc[T]) (max Optional[T])

func (Stream[T]) Min

func (s Stream[T]) Min(less LessFunc[T]) (min Optional[T])

func (Stream[T]) MinMax

func (s Stream[T]) MinMax(less LessFunc[T]) (minMax Optional[MinMax[T]])

func (Stream[T]) None

func (s Stream[T]) None(f func(T) bool) (noneMatched bool)

func (Stream[T]) Range

func (s Stream[T]) Range() <-chan T

func (Stream[T]) RangeTo

func (s Stream[T]) RangeTo(ch chan<- T)

func (Stream[T]) Reduce

func (s Stream[T]) Reduce(start T, reducer func(cumulative T, next T) T) T

func (Stream[T]) Skip

func (s Stream[T]) Skip(n int) Stream[T]

func (Stream[T]) Sorted

func (s Stream[T]) Sorted(less LessFunc[T]) Stream[T]

func (Stream[T]) TakeWhile

func (s Stream[T]) TakeWhile(f func(T) bool) Stream[T]

func (Stream[T]) Transform

func (s Stream[T]) Transform(f func(T) T) Stream[T]

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Jump to

Keyboard shortcuts

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