forked from nathan7/then-queue
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (54 loc) · 1.18 KB
/
index.js
File metadata and controls
61 lines (54 loc) · 1.18 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
'use strict';
module.exports = ThenQueue
module.exports.default = ThenQueue
function ThenQueue() {
if (!(this instanceof ThenQueue)) return new ThenQueue()
this._items = new SimpleQueue();
this._waiting = new SimpleQueue();
this.length = 0
}
ThenQueue.prototype.push = function push(item) {
this.length++
var waiting = this._waiting.shift()
if (waiting) {
waiting(item)
}
else {
this._items.push(item)
}
}
ThenQueue.prototype.shift = function shift() {
this.length--
var item = this._items.shift()
if (item) {
return Promise.resolve(item)
}
else {
var waiting = this._waiting
return new Promise(function(resolve) {
waiting.push(resolve)
})
}
}
function SimpleQueue() {
this._head = [];
this._tail = [];
}
SimpleQueue.prototype.push = function push(item) {
this._tail.push(item);
}
SimpleQueue.prototype.shift = function shift() {
if (this._head.length !== 0) {
return this._head.pop();
}
if (this._tail.length === 1) {
return this._tail.pop();
}
if (this._tail.length > 1) {
var temp = this._tail.reverse()
this._tail = this._head
this._head = temp
return this._head.pop();
}
return undefined;
}