Use JAVASCRIPT. Thank You very much. Implement a queue using a circular array as
ID: 3804342 • Letter: U
Question
Use JAVASCRIPT. Thank You very much.
Implement a queue using a circular array as discussed in class. Make your queue size 5. Queue() creates an empty queue, queue is new and empty. enqueue(item) adds a new item to the queue, queue is modified. Dequeue() removes and returns an item, queue is modified. isEmpty() returns a boolean and tests for an empty queue, queue is not modified. size() returns the int size of the queue, queue is not modified print() prints the queue from front to rear, queue is not modified. Peek() prints the front element, queue is not modified. Driver should print the results of the following enqueue("dog") enqueue("cat") enqueue("mouse") enqueue("pig") enqueue("bird") size() enqueue("puppy") size() dequeue() dequeue() size() dequeue() peek() dequeue() dequeue() size() isEmpty()Explanation / Answer
var Queue = function(maxSize){
this.queue = [];
this.reset = function(){
this.tail = -1;
this.head = -1;
};
this.reset();
this.maxSize = maxSize || Queue.MAX_SIZE;
this.increment = function(number){
return (number + 1) % this.maxSize;
};
};
Queue.MAX_SIZE = Math.pow(2, 53) - 1;
Queue.prototype.enQueue = function(record){
if(this.isFull()){
throw new Error("Queue is full can't add new records");
}
if(this.isEmpty()){
this.head = this.increment(this.head);
}
this.tail = this.increment(this.tail);
this.queue[this.tail] = record;
};
Queue.prototype.setMaxSize = function(maxSize){
this.maxSize = maxSize;
};
Queue.prototype.push = Queue.prototype.enQueue;
Queue.prototype.insert = Queue.prototype.enQueue;
Queue.prototype.isFull = function(){
return this.increment(this.tail) === this.head;
};
Queue.prototype.deQueue = function(){
if(this.isEmpty()){
throw new Error("Can't remove element from an empty Queue");
}
var removedRecord = this.queue[this.head];
this.queue[this.head] = null;
if(this.tail === this.head){
this.reset();
}else{
this.head = this.increment( this.head );
}
return removedRecord;
};
Queue.prototype.pop = Queue.prototype.deQueue;
Queue.prototype.front = function(){
return this.queue[this.head] || null;
};
Queue.prototype.peak = Queue.prototype.front;
Queue.prototype.isEmpty = function(){
return this.tail === -1 && this.head === -1;
};
Queue.prototype.print = function(){
for(var i= this.head; i <= this.tail; i++){
console.log(this.queue[i]);
}
};
var q = new Queue(5);
q.enQueue("dog");
q.enQueue("cat");
q.enQueue("mouse");
q.enQueue("pig");
q.enQueue("bird");
q.size();
q.enQueue("puppy");
q.size();
q.deQueue();
q.deQueue();
q.size();
q.deQueue();
q.peek();
q.deQueue();
q.deQueue();
q.size();
q.print();
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.