-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathiteration_plus_sleep.js
70 lines (62 loc) · 1.13 KB
/
iteration_plus_sleep.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function* naturalNumbers(){
var n = 1
do {
yield n++
}while(true)
}
function *take(gen, n){
var res
while (n > 0 && !(res = gen.next()).done){
n--
yield res.value
}
}
function isGenerator(fun){
return fun.constructor.name === 'GeneratorFunction'
}
function each(gen, fun){
var res
while(!(res = gen.next()).done){
if (isGenerator(fun)){
run(fun)
}else{
fun(res.value)
}
}
}
function run(genfun){
var gen = genfun()
function next(){
var res = gen.next()
if (!res.done){
res.value(next)
}
}
next()
}
function sleep(ms){
return function(callback){
setTimeout(callback, ms)
}
}
/*
// This is an example of what you **can't** do.
run(function *(){
each(take(naturalNumbers(), 10), function(n){
// Can't `yield` unless your nearest `function` is a
// generator.
yield sleep(1000)
//^^^^^
// SyntaxError: Unexpected identifier
console.log(n)
})
console.log('Happy New Year!')
})
*/
run(function *(){
each(take(naturalNumbers(), 10), function*(n){
yield sleep(1000)
console.log(n)
})
console.log('Happy New Year!')
})