Open lskaiser opened 5 years ago
Sounds good!
/* Queue Laura Kaiser
Queue: A queue is a data structure that temporarily holds items in a first-in-first-out (FIFO) sequence.
*/
class Queue {
//This builds the container for the objects
constructor()
{
this.data = [];
}
//Adds a new element to the back of the queue using the push method.
enqueue(element)
{
this.data.push(element);
}
//Removes the element from the front of the queue using the shift method.
//by removing the first item in the array
dequeue()
{
//First checks to see if the queue is empty.
if(this.isEmpty()){
return "No elements in Queue";
}
else{
return this.data.shift();
}
}
//Returns the first element in the queue
first()
{
//Demonstrates a shortcut to writing "if-else" statement
if (this.isEmpty())
return "No elements in Queue";
return this.data[0];
}
//Returns the last element in the queue by
//calculating the length of the array and subtracting by 1
last()
{
if (this.isEmpty())
return "No elements in Queue";
return this.data[this.data.length - 1];
}
print()
{
var qString = "";
if (this.isEmpty()){
return "No elements in Queue";
}
else{
for (var i = 0; i < this.data.length; i++)
qString += this.data[i] + " ";
return qString;
}
}
//Will return a boolean. The boolean will be true
//if the queue's length = 0
isEmpty()
{
return this.data.length == 0;
}
}
/
----TEST CLASS----
/
var q = new Queue();
console.log(q.print()); //Expected Output: Receive empty queue error message
q.enqueue(10); q.enqueue(15); q.enqueue(30); console.log("The queue: "); console.log(q.print()); //Expected Output: 10 15 30
console.log("The first item: " + q.first()); //Expected Output: 10
console.log("The last item: " + q.last()); //Expected Output: 30
q.dequeue(); console.log("The queue after one dequeue: "); console.log(q.print()); //Expected Output: 15 30
I am requesting to complete a queue.