Hello, eager learners! In today's lesson, we're exploring stacks, a crucial data structure in programming. We aim to understand stacks, implement and manipulate stacks in TypeScript, and analyze their complexities. Stacks are used in various real-world applications, such as undo operations in text editors. Let's dive right in!
First and foremost, let's understand what a stack is. Imagine a stack of plates that you can only remove from the top. This concept exemplifies stacks, which follow a Last-In, First-Out (LIFO) structure. In a LIFO stack, the last item added is the first removed. For example, adding numbers 1, 2, and 3 in sequence will yield removal in the order: 3, 2, 1. Let's see an implementation in TypeScript, where we'll push (add), pop (remove), and peek (view the top) elements.
We start by introducing the Stack class that stores an array of items that are of a specific type. Utilizing a generic type <T> makes the stack versatile, allowing it to handle any data type, such as numbers, strings, or custom objects.
In TypeScript, arrays can work as stacks. They have the necessary built-in methods. However, let's implement each operation ourselves to understand this data structure better.
Let's look at how our operations look implemented in code:
-
The
pushmethod adds a new element to the top of the stack. It utilizes the built-inpushmethod of arrays to add the element to the end of theitemsarray, representing the top of the stack. -
The
popmethod removes the topmost element from the stack. It first checks if the stack is empty and returns"Underflow"if it is, indicating that there are no elements to remove. Otherwise, it removes and returns the top element of the stack. It returns the type unionT | stringfor valid data or errors (in our implementation, the"Underflow"string). -
The
peekmethod allows us to view the topmost element without removing it from the stack. It returns the element at the last index of theitemsarray, representing the top of the stack, or"Stack is empty"if the stack is empty.
