JavaScript(JS) JS implement a queue

To implement a queue data structure in JavaScript, you can use the following code:

r‮ refe‬to:theitroad.com
class Queue {
  constructor() {
    this.items = [];
  }

  enqueue(item) {
    this.items.push(item);
  }

  dequeue() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    return this.items.shift();
  }

  front() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    return this.items[0];
  }

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

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

  print() {
    let str = "";
    for (let i = 0; i < this.items.length; i++) {
      str += this.items[i] + " ";
    }
    return str;
  }
}

// Example usage:
let queue = new Queue();
console.log(queue.isEmpty()); // Output: true
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
console.log(queue.print()); // Output: 1 2 3
console.log(queue.size()); // Output: 3
console.log(queue.front()); // Output: 1
console.log(queue.dequeue()); // Output: 1
console.log(queue.print()); // Output: 2 3

In this code, we define a Queue class that has several methods:

  • constructor(): Initializes the queue with an empty array.

  • enqueue(item): Adds an item to the end of the queue.

  • dequeue(): Removes and returns the item at the front of the queue. If the queue is empty, returns the string "Queue is empty".

  • front(): Returns the item at the front of the queue without removing it. If the queue is empty, returns the string "Queue is empty".

  • isEmpty(): Returns true if the queue is empty, false otherwise.

  • size(): Returns the number of items in the queue.

  • print(): Returns a string representation of the items in the queue.

To use the queue, you can create a new instance of the Queue class and call its methods, as shown in the example usage. This will create a new empty queue, add three items to the queue, and then print and manipulate the queue using its various methods.