-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (74 loc) · 1.46 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
class QueueFull extends Error {
constructor(...params) {
super(...params);
this.name = 'QueueFull';
}
}
class QueueEmpty extends Error {
constructor(...params) {
super(...params);
this.name = 'QueueEmpty';
}
}
class Queue {
constructor(maxSize) {
this.maxSize = maxSize || 0;
this._getters = [];
this._putters = [];
this._items = [];
}
get currSize() {
return this._items.length;
}
isFull() {
if (this.maxSize === 0) {
return false;
} else {
return this._items.length >= this.maxSize;
}
}
isEmpty() {
return this._items.length === 0;
}
_put(item) {
this._items.unshift(item);
}
_get() {
return this._items.pop();
}
_wakeUp(waiters) {
if (waiters.length > 0) {
waiters.pop()();
}
}
putNowait(item) {
if(this.isFull()) {
throw new QueueFull();
}
this._put(item);
this._wakeUp(this._getters);
}
getNowait() {
if (this.isEmpty()) {
throw new QueueEmpty();
}
const item = this._get();
this._wakeUp(this._putters);
return item;
}
async put(item) {
if (this.isFull()) {
await new Promise(r => this._putters.unshift(r));
}
this.putNowait(item);
}
async get() {
if (this.isEmpty()) {
await new Promise(r => this._getters.unshift(r));
}
return this.getNowait();
}
}
module.exports.Queue = Queue;
module.exports.QueueFull = QueueFull;
module.exports.QueueEmpty = QueueEmpty;