From d9d7a1586e900e815307723e92f6f9097518dfd6 Mon Sep 17 00:00:00 2001 From: milarin Date: Fri, 6 Sep 2024 13:49:16 +0200 Subject: [PATCH] OfSeq and OfSeq2 introduced --- go.mod | 2 +- of.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index a539533..ce5d631 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module git.milar.in/milarin/channel -go 1.18 +go 1.23 diff --git a/of.go b/of.go index af33cd1..da5a7cd 100644 --- a/of.go +++ b/of.go @@ -2,6 +2,7 @@ package channel import ( "context" + "iter" "time" ) @@ -67,3 +68,32 @@ func OfMap[K comparable, V, T any](m map[K]V, unmapper func(K, V) T) <-chan T { return out } + +// OfSeq returns a channel containing all values provided by the iterator +func OfSeq[T any](seq iter.Seq[T]) <-chan T { + out := make(chan T, 10) + + defer func() { + 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], unmapper func(K, V) T) <-chan T { + out := make(chan T, 10) + + defer func() { + defer close(out) + for key, value := range seq { + out <- unmapper(key, value) + } + }() + + return out +}