-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
85 lines (83 loc) · 1.93 KB
/
index.js
File metadata and controls
85 lines (83 loc) · 1.93 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
74
75
76
77
78
79
80
81
82
83
84
85
class FastQueue {
constructor() {
this.map = {}
this.first = 0
this.last = -1
}
push(...args) {
let i = 0
if (!this.length) {
this.first = this.last = 0
this.map[this.first] = args[i++]
}
for (; i < args.length; i++) {
this.map[++this.last] = args[i]
}
}
unshift(...args) {
let i = 0
if (!this.length) {
this.first = this.last = 0
this.map[this.first] = args[i++]
}
for (; i < args.length; i++) {
this.map[--this.first] = args[i]
}
}
pop() {
const r = this.map[this.last]
delete this.map[this.last]
this.last--
return r
}
shift() {
const r = this.map[this.first]
delete this.map[this.first]
this.first++
return r
}
get length() {
if (this.first > this.last) return 0
return this.last - this.first + 1
}
get(x) {
return this.map[this.first + x]
}
getLast() {
return this.map[this.last]
}
forEach(fn) {
for (let i = this.first; i <= this.last; i++) {
const r = fn(this.map[i], i - this.first)
if (r === false) break
}
}
}
function executor(gf, initArgs) {
const stk = new FastQueue()
stk.push([initArgs])
while (stk.length) {
let [args, g] = stk.pop()
let obj
if (g) {
// continue previous call
obj = g.next(args)
} else {
// new call
g = gf(...args)
obj = g.next()
}
//
if (obj.done) {
if (stk.length) {
stk.getLast()[0] = obj.value
} else {
return obj.value
}
} else {
stk.push([null, g])
stk.push([obj.value, null])
}
}
}
module.exports = executor