-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathrepeat-function.go
58 lines (48 loc) · 903 Bytes
/
repeat-function.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"math/rand"
)
func main() {
take := func(
done <-chan interface{},
valueStream <-chan interface{},
limit int,
) <-chan interface{} {
takeStream := make(chan interface{})
go func() {
defer close(takeStream)
for i := 0; i < limit; i++ {
select {
case <-done:
return
case takeStream <- <-valueStream:
}
}
}()
return takeStream
}
repeatFn := func(
done <-chan interface{},
fn func() interface{},
) <-chan interface{} {
valueStream := make(chan interface{})
go func() {
defer close(valueStream)
for {
select {
case <-done:
return
case valueStream <- fn():
}
}
}()
return valueStream
}
done := make(chan interface{})
defer close(done)
rand := func() interface{} { return rand.Intn(10) }
for num := range take(done, repeatFn(done, rand), 10) {
fmt.Printf("%v ", num)
}
}