TypeScript: Implement a Stack

1. Introduction

A stack is a fundamental data structure that allows operations at one end, often referred to as the "top". The stack operates under the Last In First Out (LIFO) principle. In this tutorial, we'll create a basic stack in TypeScript, utilizing its type-checking capabilities for added robustness.

2. Program Overview

The stack will support three primary operations:

1. push: To add an element to the top.

2. pop: To remove and return the top element.

3. peek: To view the top element without removing it.

We'll use an array to back our stack implementation and TypeScript interfaces to ensure type safety.

3. Code Program

// Define the Stack class and its methods
class Stack<T> {
    private items: T[] = []; // Initialize an empty array to store stack items

    // Pushes a new item onto the stack
    push(element: T): void {
        this.items.push(element);
    }

    // Pops the top item off the stack and returns it
    pop(): T | undefined {
        return this.items.pop();
    }

    // Views the top item without popping it
    peek(): T | undefined {
        return this.items[this.items.length - 1];
    }

    // Checks if the stack is empty
    isEmpty(): boolean {
        return this.items.length === 0;
    }

    // Returns the size of the stack
    size(): number {
        return this.items.length;
    }
}

// Test the Stack class
const numberStack = new Stack<number>();
console.log("Pushing 5 onto the stack");
numberStack.push(5);
console.log("Pushing 8 onto the stack");
numberStack.push(8);
console.log(`Top element: ${numberStack.peek()}`);
console.log(`Popped element: ${numberStack.pop()}`);
console.log(`Stack size: ${numberStack.size()}`);

Output:

Pushing 5 onto the stack
Pushing 8 onto the stack
Top element: 8
Popped element: 8
Stack size: 1

4. Step By Step Explanation

1. We start by defining a generic Stack class. The <T> syntax means this class can be used with any type T, such as numbers, strings, or even custom objects.

2. Our stack class contains a private array called items that will store our stack's contents.

3. The push method adds an item to the end of the items array.

4. The pop method removes and returns the last item from the items array, which represents the top of the stack.

5. The peek method returns the last item of the items array without removing it, offering a view of the stack's top.

6. The isEmpty method determines if the stack is devoid of elements.

7. The size method reports how many elements the stack holds.

8. Finally, we test our stack with some numbers, pushing them onto the stack, peeping at the top, and popping elements off, illustrating the LIFO behavior.

Comments