Junior — Middle+
Merging data from multiple channels into a single stream
livecode
Task condition
Given two input channels in1 and in2, and one output channel out. It is required to write a function merge that will listen to both input channels simultaneously and redirect the received values into a single output channel.
package main
import (
"fmt"
"math/rand"
"time"
)
func merge(ch ...<-chan int) <-chan int {
out := make(chan int)
// Here you need to implement logic that waits for data from all passed channels
// and sends it to the out channel
return out
}
func source(sourceFunc func(int) int) <-chan int {
ch := make(chan int)
go func() {
defer close(ch)
for i := 0; i < 10; i++ {
ch <- sourceFunc(i)
time.Sleep(time.Duration(rand.Intn(3)) * time.Second)
}
}()
return ch
}
func main() {
rand.Seed(time.Now().UnixMilli())
in1 := source(func(_ int) int {
return rand.Intn(7)
})
in2 := source(func(i int) int {
return i
})
out := merge(in1, in2)
for val := range out {
fmt.Println("Value:", val)
}
}