-
Notifications
You must be signed in to change notification settings - Fork 1
/
12-iterator.js
44 lines (35 loc) · 859 Bytes
/
12-iterator.js
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
import chan from '../../src'
import {p, sleep} from '../utils'
class ClosedRangeIterator {
constructor(countFrom, upto) {
this._i = countFrom - 1
this._upto = upto
}
next() {
if (++this._i > this._upto) {
p(' -> iterator finished')
return { value: undefined, done: true }
} else {
p(' -> producing new value:', this._i)
return { value: this._i, done: false }
}
}
}
async function consumer(ch) {
while (ch.CLOSED != await ch.take()) {
p('<- got value:', ch.value)
await sleep(50)
}
p('<- chan closed')
}
async function run() {
p('--- chan.fromIterable')
let ch1 = chan.fromIterable('abcde')
await consumer(ch1)
p('--- chan.fromIterator')
let iter = new ClosedRangeIterator(3, 7)
let ch2 = chan.fromIterator(iter)
await sleep(500)
await consumer(ch2)
}
run().catch(p)