Sobes.tech
Junior — Middle

How can a queue data structure be implemented in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, a queue can be implemented using an array, utilizing the push method to add to the end and the shift method to remove from the beginning, which corresponds to the FIFO (First In, First Out) principle.

Example of a simple queue implementation:

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

  enqueue(element) {
    this.items.push(element); // add to the end
  }

  dequeue() {
    if(this.isEmpty()) {
      return null;
    }
    return this.items.shift(); // remove from the beginning
  }

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

  peek() {
    return this.isEmpty() ? null : this.items[0];
  }
}

// Usage:
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 1
console.log(queue.peek());    // 2

For more efficient implementation (to avoid shifting elements with shift), a linked list or a queue with two indices can be used.