-
Notifications
You must be signed in to change notification settings - Fork 2
/
7.3-tamper-free-queue.js
46 lines (37 loc) · 955 Bytes
/
7.3-tamper-free-queue.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
class Queue {
constructor(executor) {
const queue = [];
let resolveQueue = [];
const enqueue = (item) => {
queue.push(item);
if (resolveQueue.length) {
const resolve = resolveQueue.shift();
resolve(queue.shift());
}
}
executor(enqueue);
this.dequeue = () => {
if (queue.length) {
const item = queue.shift();
if (resolveQueue.length) {
const resolve = resolveQueue.shift();
resolve(queue.shift());
}
return Promise.resolve(item);
}
return new Promise((resolve, reject) => {
resolveQueue.push(resolve);
});
}
}
}
const queue = new Queue((enqueue) => {
enqueue(1);
enqueue(3);
setTimeout(() => enqueue(6), 2000);
setTimeout(() => enqueue(3), 0);
})
console.log(await queue.dequeue());
console.log(await queue.dequeue());
console.log(await queue.dequeue());
console.log(await queue.dequeue());