-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (67 loc) · 1.56 KB
/
index.js
File metadata and controls
73 lines (67 loc) · 1.56 KB
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
71
72
73
function* test() {
let a = 1 + 2
yield 2
yield 3
}
// 上述代码经过 babel 编译后
function _test() {
let a
return generator(function (context) {
for (;;) {
switch ((context.prev = context.next)) {
case 0:
a = 1 + 2
context.next = 4
return 2
case 4:
context.next = 6
return 3
case 6:
case 'end':
return context.stop()
}
}
})
}
/**
* 简单实现上述中的 generator
* @param {Function} cb 回调函数
*/
function generator(cb) {
return (function () {
let obj = {
next: 0,
stop: function () {}
}
return {
next: function () {
let ret = cb(obj)
if (ret === undefined) {
return {
value: undefined,
done: true
}
}
return {
value: ret,
done: false
}
}
}
})()
}
// 测试
let g = _test()
console.log(g.next())
console.log(g.next())
console.log(g.next())
console.log()
function* test2() {
let x = yield 1
return x
}
let g2 = test2()
let ret = g2.next()
console.log(ret)
console.log(g2.next(ret.value + 100)) // { value:101, done:true }
console.log(g2.next())