The Second Article on the JS:DS series. In this write up we are going to see the Queue Data Structure implementation in javascript and we use arrays for that.
For Stack Data Structure in JS. Please read in the below post.
JS:DS - Stack Data Structure in JavaScript
Saravana Kumar Putta Selvaraj ・ Jun 1 '20 ・ 1 min read
What is Queue?
The queue is a data structure to store the data in the order of insertion where the item gets inserted at the first into the queue will be the first one to be removed.
In shorter terms First In First Out(FIFO).
How are we going to implement it?
The following are the methods we are going to have in Queue DS.
initialize — Initialize the storage and queue size
enqueue — push item to the queue
dequeue — remove the first pushed item from the queue
getQueueSize — Get the current queue size
initialize
- @parmas — size — Queue Size
- storage — an array to store the items of the queue DS
- currentQueueSize — to track the size of the queue
- queueSize — application users can set the predefined size of the queue
class Queue {
constructor(size) {
this.storage = [];
this.currentqueueSize = 0;
this.queueSize = size ? size : 10;
}
}
enqueue - Add items to the queue
- Check the current size of the queue is less than the actual queue size.
- If the above condition gets a pass, increase the current queue size by 1, and push the item to the Queue.
- Else throw the error saying that the queue is full!
class Queue {
constructor(size) {
this.storage = [];
this.currentqueueSize = 0;
this.queueSize = size ? size : 10;
}
enqueue(item) {
if (this.currentqueueSize < this.queueSize) {
this.queueSize++;
this.storage.push(item);
} else {
throw 'Cannot enqueu. Since the Queue is full!'
}
}
}
dequeue - Remove items from the queue
- Check the current size of the queue is greater than 0.
- If the above condition gets a pass, decrease the current queue size by 1, and remove the item from the first position in an array using shift().
- Else throw the error saying that the queue is empty!
class Queue {
constructor(size) {
this.storage = [];
this.currentqueueSize = 0;
this.queueSize = size ? size : 10;
}
dequeue() {
if (this.currentqueueSize > 0) {
this.currentqueueSize--;
return this.storage.shift();
}
throw 'Cannot dequeue. Since the Queue is empty!'
}
}
getQueueSize
Return the current Queue size from the initialization part
class Queue {
constructor(size) {
this.storage = [];
this.currentqueueSize = 0;
this.queueSize = size ? size : 10;
}
getQueueSize() {
return this.currentqueueSize;
}
}
Complete code in below gist
This article is made with ❤️ and am always thankful for the dev community around us!
Please follow me to get to know about latest write ups.
Top comments (0)