Data Structures: The Stack in TypeScript

Data Structures: The Stack in TypeScript

Hey there, dear code wrangler! Ever found yourself in a situation where you're going through a pile of books and can only pick the one at the top? That, my friend, is a real-life analogy of a "Stack" in data structures. Let's dive right into the world of Stacks, TypeScript-style. Buckle up!

What's a Stack Anyway?

Imagine a stack of pancakes. You can't just sneak one out from the middle, can you? Nah! You gotta start from the top. In computer science, a Stack is a linear data structure that follows the Last In First Out (LIFO) principle. What goes in last, comes out first. It's like a magic show, but with data.

Why Use a Stack?

  1. Undo Operations: Ever hit 'ctrl + z' (or 'cmd + z' for the Mac lovers) and watched your last action disappear? That's a stack, buddy!
  2. Expression Evaluation & Conversion: Converting infix expressions to postfix? Stacks got your back!
  3. Memory Management: Ever heard of a 'call stack'? Yup, stacks again.

Using a Stack in TypeScript

Alright, enough with the chit-chat. Let's get down to brass tacks and cook up a simple Stack in TypeScript.

Setting up the Stack

Let's start with the basics:

export class Stack {
	items: any[]

	constructor() {
		this.items = []

	push(element: any) {

	pop() {
		return this.items.pop()

	peek() {
		return this.items[this.items.length - 1]

	isEmpty() {
		return this.items.length === 0

	size() {
		return this.items.length

	print() {


Just like that, we've got a generic Stack class. Use it with any type - numbers, strings, you name it.

A Quick Stack-y Example

Imagine we're checking for balanced parentheses in an expression. A classic job for our Stack!

function areParenthesesBalanced(expression: string): boolean {
    const stack = new Stack<char>();

    for (let char of expression) {
        if (char === '(') {
        } else if (char === ')') {
            if (stack.isEmpty()) return false;
    return stack.isEmpty();

Just pass an expression to areParenthesesBalanced and see the magic unfold!

Tips 'n' Tricks

Type Safety: Always remember, TypeScript's static typing is like a guardian angel. Use it wisely. Generics, like in our Stack class, can save you from a world of pain. Keep It Clean: Don't just pile everything onto your stack without rhyme or reason. Know when to push and when to pop. Big O: Keep an eye on time complexity. A stack's primary operations (push, pop, peek) are often O(1), but it doesn't hurt to be vigilant.

Wrapping Up

Stacks, though simple at heart, can be a game-changer in solving a myriad of problems. And with TypeScript's static type checking, the journey becomes a tad smoother and a lot more fun. So next time you're knee-deep in code, and something seems stack-able, you know what to do!

Remember, every data structure has its day. Today, it's the Stack's turn to shine. Till next time, keep popping (and pushing)!