This is the first of a multi-part series where we will be implementing some
popular data structures using TypeScript. This week’s focus is Stack data
structure.
What is a Stack?
A stack is a linear data structure that follows the order of Last In First
Out(LIFO). This means the first inserted element will be removed last. You can
think of the stack as a pile of books that are placed on top of one another.
Use cases of Stack data structure.
The stack can be useful in a situation where the order of the data inserted is
important. Following are some common scenarios where stack can be useful.
Javascript call stack - Keep track of function calls
Undo/Redo - Undo by removing the last element in the stack, and redo by
inserting the last removed item from the stack
Reversing - Reverse a string
Basic operations of a Stack
A stack should be able to perform the following basic operations.
Push: Add an element to the top of a stack
Pop: Remove an element from the top of a stack
IsEmpty: Check if the stack is empty
IsFull: Check if the stack is full
Peek: Get the value of the top element without removing it
Implementation
In order to implement the Stack data structure, we can follow the following
steps.
Define a variable called TOP to keep track of the first element in the stack
When initialized, set the value of TOP to -1. Later we can use this to
check if the stack is empty or not.
Whenever an item is pushed, increase the value of **TOP** by 1 and place the
new element at the position pointed by TOP. Also, check if the stack is full
before pushing a new element.
Whenever an item is popped, decrease the value of TOP by 1. Also, check if
the stack is empty before popping an element.
Following is the TyepeScript implementation of the Stack data structure
Testing
Now that we have implemented the Stack data structure using TypeScript, it is
time to test the functionalities of our Stack. We will be using Jest to write
some important test cases.