Implementing Queue in JavaScript

In this blog, we’re going to discuss how to implement queues in JavaScript. Specifically, we’ll cover two approaches: one using an array and another using a linked list.

Implementing Queue using Array in JavaScript

Let’s kick things off with a simple implementation using an array. In JavaScript, arrays are versatile data structures, making them suitable for implementing queues. Here’s a basic example:

class Queue {
  constructor() {
    this.items = [];
  }

  // Add an element to the queue
  enqueue(element) {
    this.items.push(element);
  }

  // Remove and return the front element from the queue
  dequeue() {
    if (this.isEmpty()) {
      console.log("Queue is empty");
      return null; // or throw new Error("Queue is empty");
    }
    return this.items.shift();
  }

  // Return the front element without removing it
  front() {
    if (this.isEmpty()) {
      console.log("Queue is empty");
      return null; // or throw new Error("Queue is empty");
    }
    return this.items[0];
  }

  // Check if the queue is empty
  isEmpty() {
    return this.items.length === 0;
  }

  // Return the size of the queue
  size() {
    return this.items.length;
  }

  // Print the elements of the queue
  print() {
    console.log(this.items.join(" "));
  }
}

// Example usage:
const queue = new Queue();

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

console.log("Front element:", queue.front()); // Front element: 10

console.log("Queue size:", queue.size()); // Queue size: 3

console.log("Dequeue:", queue.dequeue()); // Dequeue: 10

queue.print(); // 20 30

In this implementation, we have a Queue class with methods for enqueue, dequeue, checking if the queue is empty, getting the front element, and more.

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us

Leave a Comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Scroll to Top