Professional Documents
Culture Documents
Implementing A Queue in JavaScript
Implementing A Queue in JavaScript
A queue is a list — similar to the real world queue. The one who gets into the
queue first is the one who is removed first from the queue.
Technically speaking, this process is called first in, first out (FIFO). The element
which is inserted first will be removed first from the list
Elements are always added to the end of the list and removed from the front of
the list.
constructor(){
this.data = [];
this.rear = 0;
this.size = 10; }}
data → is the list in which we store our elements
rear → is used to store the position in which the next element will be stored
In addition to the above case, we need to check if the queue is full or not so it
avoids overflow.
enqueue(element) {
return this.rear; }
this.rear = this.rear-1;
return this.data.shift();
}}
Reset Queue
Delete all elements of the queue and set the rear to 0.
clear() {
this.data.length = 0;
this.rear = 0;}
The End
Let’s combine all the above code together
class
Queue
{
constructor(){
this.data = [];
this.rear = 0;
this.size = 10;
}
enqueue(element) {
if(this.rear < this.size ) {
this.data[this.rear] = element;
this.rear = this.rear + 1;
}
}
length() {
return this.rear;
}
isEmpty() {
this.rear = this.rear-1;
return this.data.shift();
}
}
print() {
for(let i =0; i < this.rear; i++) {
console.log(this.data[i]);
}
}
clear() {
this.data.length = 0;
this.rear = 0;
}
}