Implement Queue data structure in Javascript
Queue in javascript : hashnode link
The Queue
is the data structure that works on FIFO Principle, which is the abbreviation for "First In First Out".
Queues can have various applications:
Let's suppose you are making a service that requires you to send the email, but you don't want your program to wait for mailing to finish. Then you can send that particular task to the mailing queue and it will take control of sending all the mails in FIFO manner.
Now let's implement some functionality of the queue
The queue has some operations such as:
-
enqueue
which will add the elements at the end of the queue. -
Dequeue
removes the element from the start of the queue. -
Front
To find out the element at the beginning of the queue. -
Size
function will give you the size of the queue. -
Empty
function will check if the queue is empty or not, and return us the boolean value. -
Print
function will print the whole queue for us.
function Queue() {
let items = [];
this.enqueue = function (element) {
items.push(element);
};
this.dequeue = function () {
return items.shift();
};
this.front = function () {
return items[0];
};
this.size = function () {
return items.length;
};
this.isEmpty = function () {
return items.length === 0;
};
this.print = function () {
console.log(items);
};
}
Result :
const q = new Queue();
q.enqueue(10); // [10] : enqueue from end
q.enqueue(20); // [ 10, 20] : enqueue from end
q.dequeue(); // [ 20] : dequeue from start
q.print(); // prints the whole queue
console.log(q.size()); // return the size : i.e 1
© Jagdish Parihar.RSS