Lesson Overview and Goal

Welcome! Today, we're exploring the concept of queues in TypeScript, a fundamental data structure that processes elements in a first-in, first-out (FIFO) order, akin to a line at a food truck. We aim to learn how to implement, analyze, and manipulate queues in TypeScript, with a focus on type annotations to ensure robust code. Let's dive in!

Introduction to Queues

Imagine you're in line for a roller coaster. The first person in line is always the first to ride. queues in programming follow this principle, making the queue concept relatively easy to grasp and powerful to use.

Implementing a Queue in TypeScript

queues can be efficiently implemented in TypeScript using arrays with type annotations for added safety. Take a look at this simple Queue class:

class Queue<T> {
    private data: T[] = []; // A queue is constructed as an array of type T

    enqueue(element: T): void {
        // The push() method adds an element at the end
        this.data.push(element); 
    }

    dequeue(): T | string {
        if(this.isEmpty()) 
            return "Underflow"; // If the queue is empty
        // The shift() method removes an element from the start
        return this.data.shift() as T; 
    }

    isEmpty(): boolean {
        // The length property checks if the queue is empty
        return this.data.length === 0; 
    }
}

This Queue class offers enqueue and dequeue methods to manage the queue's state with type safety.

Queue Enqueue Operation

The enqueue method adds to the queue's end. Here's how it works:

let queue = new Queue<number>();
queue.enqueue(1); // 1 is added at the end of the queue
queue.enqueue(2); // 2 is now at the end, and 1 moves a step forward 
queue.enqueue(3); // 3 joins at the end, pushing 2 and 1 further up
console.log(queue); // {data: [1, 2, 3]}

The order of the queue is {data: [1, 2, 3]}, reflecting the FIFO principle.

Queue Dequeue Operation

Consequently, the dequeue method removes an element from the queue's start:

let queue = new Queue<number>();
queue.enqueue(1); // 1 is the first to join the queue
queue.enqueue(2); 
queue.enqueue(3);
queue.dequeue(); // 1 is removed as it was the first to join
console.log(queue); // {data: [2, 3]}

Now, the queue reads {data: [2, 3]}, with 1 dequeued.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal