channel/of.go

54 lines
1.2 KiB
Go
Raw Normal View History

2022-02-09 12:10:02 +01:00
package channel
2022-02-09 12:17:49 +01:00
import (
"context"
"time"
)
2022-02-09 12:10:02 +01:00
// Of returns a channel containing all values
func Of[T any](values ...T) <-chan T {
2022-02-09 12:17:49 +01:00
return OfDelayed(0, values...)
2022-02-09 12:10:02 +01:00
}
// OfDelayed behaves like Of but with a pre-defined delay between each value
func OfDelayed[T any](delay time.Duration, values ...T) <-chan T {
2022-02-17 09:17:23 +01:00
return OfDelayedFunc(func(value T) time.Duration { return delay }, values...)
2022-02-09 12:10:02 +01:00
}
// OfDelayedFunc behaves like OfDelayed but accepts a function to determine the delay
func OfDelayedFunc[T any](delayFunc func(value T) time.Duration, values ...T) <-chan T {
out := make(chan T, len(values))
go func(out chan T, values []T) {
for i, value := range values {
out <- value
if i < len(values)-1 {
time.Sleep(delayFunc(value))
}
}
close(out)
}(out, values)
return out
}
// OfFunc returns a channel containing the return values of successively calling f
// It closes the channel as soon as ctx is done
func OfFunc[T any](ctx context.Context, buffer int, f func() T) <-chan T {
out := make(chan T, buffer)
go func() {
defer close(out)
for ctx.Err() == nil {
select {
case out <- f():
case <-ctx.Done():
return
}
}
}()
return out
}