forked from ericu/jv-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
43 lines (36 loc) · 876 Bytes
/
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
function Queue(capacity) {
this.q = new Array(capacity);
this.next = 0;
this.size = 0;
this.isFull = function() {
return this.size >= this.q.length;
}
this.isEmpty = function() {
return this.size <= 0;
}
this.push = function(elt) {
if (this.isFull()) {
throw new Error("Can't push on a full queue!");
}
this.q[(this.next + this.size++) % this.q.length] = elt;
}
this.pop = function() {
if (this.isEmpty()) {
throw new Error("Can't pop from an empty queue!");
}
var ret = this.q[this.next];
this.next = (this.next + 1) % this.q.length;
--this.size;
return ret;
}
this.peek = function() {
if (this.isEmpty()) {
throw new Error("Can't peek at an empty queue!");
}
return this.q[this.next];
}
this.clear = function() {
this.next = this.size = 0;
}
return this;
}