-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue2.js
49 lines (42 loc) · 1.08 KB
/
queue2.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
function Queue() {
this._oldestIndex = 1;
this._newestIndex = 1;
this._storage = {};
}
Queue.prototype.size = function() {
return this._newestIndex - this._oldestIndex;
};
Queue.prototype.enqueue = function(data) {
this._storage[this._newestIndex] = data;
this._newestIndex++;
};
Queue.prototype.dequeue = function() {
var oldestIndex = this._oldestIndex,
newestIndex = this._newestIndex,
deletedData;
if (oldestIndex !== newestIndex) {
deletedData = this._storage[oldestIndex];
delete this._storage[oldestIndex];
this._oldestIndex++;
return deletedData;
}
};
Queue.prototype.printQueue = function() {
console.log(this);
};
//Test it
queue = new Queue();
console.log("dequeue from empty :",queue.dequeue());
queue.enqueue(5);
queue.printQueue();
queue.enqueue(6);
queue.printQueue();
queue.enqueue(7);
queue.enqueue(8);
queue.printQueue();
console.log("dequeue :",queue.dequeue());
queue.printQueue();
console.log("dequeue :",queue.dequeue());
queue.printQueue();
queue.enqueue(4);
queue.printQueue();