In this chapter of Learning Data Structures with Typescript, we will be
implementing and testing the Queue data structure.
What is a Queue?
A queue is a linear data structure that follows the order of First In First
Out(FIFO). This means the first inserted element will be removed first. You can
think of the queue as a line of people waiting to purchase movie tickets at a
cinema theater.
Use cases of Queue data structure.
The queue can be useful in a situation where the order of the data inserted is
important. Following are some common scenarios where queues can be useful.
Handling website traffic
Maintaining the playlist in media players
Managing requests on a single shared resource
Basic operations of a Queue
A queue should be able to perform the following basic operations.
Enqueue: Add an element to the end of the queue
Dequeue: Remove an element from the front of the queue
IsEmpty: Check if the queue is empty
IsFull: Check if the queue is full
Peek: Get the value of the first element without removing it
Implementation
In order to implement the Queue data structure, we can follow the following
steps.
Define 2 variables called FRONT and REAR to keep track of the first and
last element of the queue
When initialized, set the value of FRONT, REAR to -1. Later we can use
this to check if the queue is empty or not.
Whenever an item is enqueued, increase the value of REAR by 1 and place the
new element at the position pointed by REAR. If the queue is empty, increase
the value of FRONT by 1. Also, check if the queue is full before pushing a
new element.
Whenever an item is dequeued, decrease the value of REAR by 1. Also, check
if the queue is empty before dequeuing an element. When dequeuing the last
element, set the FRONT back to 0.
Following is the TyepeScript implementation of the Queue data structure
Testing
Now that we have implemented the Queue data structure using TypeScript, it is
time to test the functionalities of our Queue. We will be using Jest to test
them.