channel/of.go

100 lines
2.1 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"
2024-09-06 13:49:16 +02:00
"iter"
2022-02-09 12:17:49 +01:00
"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) {
2022-02-17 09:18:37 +01:00
defer close(out)
2022-02-09 12:10:02 +01:00
for i, value := range values {
out <- value
if i < len(values)-1 {
time.Sleep(delayFunc(value))
}
}
}(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
}
2022-04-25 20:04:14 +02:00
// OfMap returns a channel containing the return values of the unmapper function
// applied to any key-value pair in m
// The order is random
func OfMap[K comparable, V, T any](m map[K]V, unmapper func(K, V) T) <-chan T {
out := make(chan T, len(m))
2024-09-09 10:34:38 +02:00
go func() {
2022-04-25 20:04:14 +02:00
defer close(out)
for k, v := range m {
out <- unmapper(k, v)
}
}()
return out
}
2024-09-06 13:49:16 +02:00
// OfSeq returns a channel containing all values provided by the iterator
func OfSeq[T any](seq iter.Seq[T], buffer int) <-chan T {
out := make(chan T, buffer)
2024-09-06 13:49:16 +02:00
2024-09-09 10:34:38 +02:00
go func() {
2024-09-06 13:49:16 +02:00
defer close(out)
for v := range seq {
out <- v
}
}()
return out
}
// OfSeq2 returns a channel containing the return values of the unmapper function
// when provided with the values of the iterator
func OfSeq2[K comparable, V, T any](seq iter.Seq2[K, V], buffer int, unmapper func(K, V) T) <-chan T {
out := make(chan T, buffer)
2024-09-06 13:49:16 +02:00
2024-09-09 10:34:38 +02:00
go func() {
2024-09-06 13:49:16 +02:00
defer close(out)
for key, value := range seq {
out <- unmapper(key, value)
}
}()
return out
}