fixed bugs in TeeMany

This commit is contained in:
Timon Ringwald 2022-08-28 15:28:33 +02:00
parent 81d06f550c
commit 0a42c8cf0a

View File

@ -39,21 +39,28 @@ func Tee[T any](source <-chan T) (<-chan T, <-chan T) {
// TeeMany returns a given amount of channels which all receive all values from source. // TeeMany returns a given amount of channels which all receive all values from source.
// It's basically a copy function for channels // It's basically a copy function for channels
func TeeMany[T any](source <-chan T, amount int) []<-chan T { func TeeMany[T any](source <-chan T, amount int) []<-chan T {
outs := make([]chan T, amount) outputs := make([]chan T, amount)
for i := range outputs {
outputs[i] = make(chan T, cap(source))
}
go func() { go func() {
defer func() { defer func() {
for _, out := range outs { for _, out := range outputs {
close(out) close(out)
} }
}() }()
for value := range source { for value := range source {
for _, out := range outs { for _, out := range outputs {
out <- value out <- value
} }
} }
}() }()
return (interface{}(outs)).([]<-chan T) readOnlyOutputs := make([]<-chan T, 0, amount)
for _, out := range outputs {
readOnlyOutputs = append(readOnlyOutputs, out)
}
return readOnlyOutputs
} }