Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to create a queue, then enqueue and dequeue elements in TypeScript

1 Answer

0 votes
class Queue<T> {
    private items: T[] = [];

    enqueue(element: T): void {
        this.items.push(element);
    }

    dequeue(): T | undefined {
        if (this.isEmpty()) {
            console.error("Queue is empty. Cannot dequeue.");
            return undefined;
        }
        return this.items.shift();
    }

    peek(): T | undefined {
        if (this.isEmpty()) {
            console.error("Queue is empty. Nothing to peek.");
            return undefined;
        }
        return this.items[0];
    }

    isEmpty(): boolean {
        return this.items.length === 0;
    }

    size(): number {
        return this.items.length;
    }

    clear(): void {
        this.items = [];
    }

    print(): void {
        if (this.isEmpty()) {
            console.log("Queue is empty.");
        } else {
            console.log("Queue contents:", this.items.join(", "));
        }
    }
}

const queue = new Queue<number>();

// Enqueue elements
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.print();
// Dequeue elements
console.log("Dequeued:", queue.dequeue()); 
console.log("Dequeued:", queue.dequeue()); 

// Peek at the front element
console.log("Front element:", queue.peek()); 

// Check if the queue is empty
console.log("Is queue empty?", queue.isEmpty()); 

// Get the size of the queue
console.log("Queue size:", queue.size()); 

// Clear the queue
queue.clear();
console.log("Is queue empty? after clearing:", queue.isEmpty()); 




/*
run:

"Queue contents:",  "10, 20, 30, 40" 
"Dequeued:",  10 
"Dequeued:",  20 
"Front element:",  30 
"Is queue empty?",  false 
"Queue size:",  2 
"Is queue empty? after clearing:",  true 

*/


 



answered Aug 23, 2025 by avibootz
...