Data Structures Pt.1: “Queues”
If you are in the process of your job search and job interviews, I am sure you’ve come across the word Data Structures. What are they and how can we use them in our daily programming. I’d like to start a blog series on Data Structures, touching on a different type each week. We will be using Javascript as the programming language as we dive into Data Structures. Today we will be talking about Queues so let’s get started.
What are Data Structures? Data structures are ways of organizing information with optimal ‘runtime complexity’ for adding and or removing records.
What is a queue? In Javascript, an array can do a tremendous amount of things, and a queue is only a partial ability of what an array is capable of. However, in a technical interview, you will still be asked to build queues from scratch, to show your insight knowledge. A queue can be described as a container, where records or pieces of data entry on one end and exit on the other. An analogy would be to think of a line in which you are waiting at the store or to get something at the other end. The process of adding a record into a queue is known as Enqueuing, and removing a record is known as dequeuing. Queuing follows the directive of first in first out process, or ‘FIFO’. In Javascript when we want to implement a queue, we take an array and restrict the methods that interact with that array.

Making a Queue: To make a queue, we will start by creating a new empty queue instance, and adding and removing a record from that queue, with methods. First, we start by creating a class called Queue. Next, we need a place to store our data which would be an empty array, inside our constructor method.

Adding the methods: Then we need to add our two methods. One for adding to the queue and one for removing from the queue. The add method will take in a record parameter that needs to be added to the queue, and in that method, we simply unshift the record. For our remove method, we simply return this of data and pop the record out like so.

Now that we have our methods and created a new instance of our class Queue we can call the methods we implemented. Here we have our queue class, notice when we call our methods to add and remove, that it follows the first in first out style.

Congratulations you have created a Queue. We can take it a step further and a peek method, but we can technically do that by just calling the q object. Thank you and please stay tuned for my next blog on “stacks”.