This repository has been archived by the owner on Dec 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (64 loc) · 1.83 KB
/
index.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* eslint-disable require-yield, no-constant-condition */
'use strict'
const INIT = Symbol.for('INIT')
class RunGen {
constructor() {
this.run = this.run.bind(this)
}
* wrap(value) {
return value
}
* resolve(result, iterator) {
if (result.done) {
return result.value.then(res => this.run(this.wrap(res)))
}
return result.value.then(res => this.run(iterator, res))
}
* init(iterator, result) {
iterator[INIT] = true
return result
}
* runner(iterator, result, args) {
if (result.value && typeof result.value.then === 'function') {
return yield* this.resolve(result, iterator)
}
if (result.done) {
return result.value
}
yield result.value
return yield* this.runner(iterator, iterator.next(args || result.value))
}
* _start(iterator, ...args) {
if (args.length < 2) {
args = args[0]
}
if (iterator[INIT]) {
return yield* this.runner(iterator, iterator.next(args))
}
return yield* this.runner(
iterator, yield* this.init(iterator, iterator.next()), args
)
}
* start(iterator, ...args) {
if (typeof iterator === 'function') {
return yield* this.start(iterator(...args))
}
return yield* this._start(iterator, ...args)
}
_run(...args) {
const iterator = this.start(...args)
while (true) {
const result = iterator.next()
if (result.done) {
return result.value
}
}
}
run(...args) {
return Promise.resolve().then(() => this._run(...args))
}
}
const runGen = new RunGen()
runGen.run.RunGen = RunGen
runGen.run.INIT = INIT
module.exports = runGen.run