Queues and Javascript
Queue
A queue, in computer science, is a data structure that behaves very much like queues you see in everyday life, where the first one on the line is the first one to be served, this kind of modus operandi is called FIFO (first-in-first-out).
A queue just like a stack represents a collection of items. The main difference between a queue and a stack is the order in which elements are removed.
if you want to know more about stacks, check my previous post at https://garycordero1690.medium.com/stacks-and-javascript-dc33f12cb0d0
Queue Basic Operations
- Enqueue()/Add(), to add an element to the end of the queue.
- Dequeue()/Remove(), to remove the element at the front of the queue.
- Peek(), to see the element at the front of the queue.
Implementing a Queue in Javascript
Unfortunately, as with stack, Javascript does not provide a predefined way to use queues in our code as other programming languages do, but it gives us all the tools to implement it.
Let’s start by creating a Queue class and defining an array attribute called to hold our collection of items.
Now let’s implement the rest of the behavior.
Enqueue(), to add an element to the end of the queue.
Dequeue(), to remove the element at the front of the queue.
Peek(), to see the element at the front of the queue.
The whole body of the class would be as follow.
Conclusion
Queues are powerful data structures that give a strong sense of security when implemented correctly due to the constraint on their operations. Definitely, useful for operations that have tasks that don't need to be executed instantly but need to be executed in a “First in First out” way. Operating Systems tend to have a queue of the processes that are waiting to be executed or for a particular event.