How to implement a queue in JS
A queue is a data structure following the First In First Out principle (FIFO), like a line at a store.
A queue is a simple linear data structure that works like a line at a store. The first person to join the line is the first to leave, and the last person has to wait for everyone else. This is called the First In First Out (FIFO) principle. Queues are often used in programming for things like task scheduling, searching algorithms, and buffering data streams.
View Source CodeBasic Operations of a Queue
A queue typically supports the following operations:
- Enqueue: Add an item to the end of the queue.
- Dequeue: Remove an item from the front of the queue.
- Peek/Front: Get the front item of the queue without removing it.
- IsEmpty: Check if the queue is empty.
- Size: Get the number of items in the queue.
- Last: Get the item at the end of the queue.
Let's Implement a Queue in JavaScript/TypeScript
JavaScript does not have a built-in Queue class, but you can easily implement one using an array or a linked list. Here, we'll use an array for simplicity.
export class Queue<T> { private items: T[]; constructor() { this.items = []; } /** * Adds an item to the end of the queue. */ enqueue(item: T) { this.items.push(item); } /** * Removes and returns the item at the front of the queue. * Returns undefined if the queue is empty. */ dequeue(): T | undefined { if (this.isEmpty) return undefined; return this.items.shift(); } /** * Returns the item at the front of the queue without removing it. * Returns undefined if the queue is empty. */ get peek(): T | undefined { return this.items[0]; } /** * Checks if the queue is empty. */ get isEmpty(): boolean { return this.items.length === 0; } /** * Returns the number of items in the queue. */ get size(): number { return this.items.length; } /** * Returns the item at the end of the queue. * Returns undefined if the queue is empty. */ get last(): T | undefined { return this.items[this.items.length - 1]; } /** * Returns the items in the queue as a string. */ printQueue() { if (this.isEmpty) return 'The queue is empty.'; return this.items.toString(); } }
Example Usage
Below is an example of how you can use the Queue
class.
const numberQueue = new Queue<number>(); // Enqueue numbers numberQueue.enqueue(1); numberQueue.enqueue(2); numberQueue.enqueue(3); // Output: Peek: 1 numberQueue.peek; // Output: Is Empty: false numberQueue.isEmpty; // Output: Size: 3 numberQueue.size; // Output: Dequeued: 1 numberQueue.dequeue(); // // Output: Queue: 2,3 numberQueue.printQueue();
Wrapping Up
Queues are not just a fundamental data structure; they are essential in various scenarios where the FIFO principle is required. Whether you're working on round-robin scheduling, implementing algorithms, or handling data streams, queues offer numerous possibilities and help you manage ordered data more effectively.
View Source Code