-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
62 lines (52 loc) · 1.79 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function Queue() {
this.items = [];
this.arrayLength = 0;
this.size = 0;
this.head = 0;
this.tail = -1;
this.enqueue = function(item) {
// We check if the array needs to grow
if(this.size === this.arrayLength) {
// We declare a new array and initialize it's slots
this.arrayLength = (this.size === 0) ? 8 : (this.size * 2);
let newArray = [];
for(let i = 0; i < this.arrayLength; i++) {
newArray[i] = undefined;
}
if(this.size > 0) {
let targetIndex = 0;
// If we wrapped...
if(this.tail < this.head) {
// Copy items[head]..items[end]
for(let i = this.head; i < this.arrayLength; i++) {
newArray[targetIndex] = this.items[i];
++targetIndex;
}
// Copy items[0]..items[tail]
for(let i = 0; i <= this.tail; i++) {
newArray[targetIndex] = this.items[i];
++targetIndex;
}
}
}
}
}
this.dequeue = function() {
let value = this.items[0];
if(typeof(value) === "object") {
if(Number.prototype.isPrototypeOf(value) ||
String.prototype.isPrototypeOf(value) ||
Boolean.prototype.isPrototypeOf(value) ||
Symbol.prototype.isPrototypeOf(value)) {
// Deep copy
value = JSON.parse(JSON.stringify(value));
} else {
// Shallow copy
value = Object.assign({}, value);
}
}
delete this.items[0];
--this.items.length;
return value;
}
}