implement queue with array in javascript

You can implement a queue data structure using an array in JavaScript using the built-in methods push() and shift().

Here's the implementation of a queue with an array:

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

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

  dequeue() {
    if(this.isEmpty())
      return "Underflow";
    return this.items.shift();
  }

  front() {
    if(this.isEmpty())
      return "No elements in Queue";
    return this.items[0];
  }

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

  printQueue() {
    let str = "";
    for(let i = 0; i < this.items.length; i++)
      str += this.items[i] +" ";
    return str;
  }
}
507 chars
33 lines

In the above implementation, enqueue() method is used to add an element to the end of the queue. dequeue() method is used to remove the first element of the queue. front() method is used to return the first element of the queue. isEmpty() method is used to check whether the queue is empty. printQueue() method is used to print all the elements of the queue.

Usage example:

index.tsx
let q = new Queue();
console.log(q.isEmpty()); // returns true
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
console.log(q.printQueue()); // returns "10 20 30 "
console.log(q.front()); // returns 10
q.dequeue();
console.log(q.printQueue()); // returns "20 30 "
console.log(q.front()); // returns 20
298 chars
11 lines

This implementation has a time complexity of O(1) for enqueue(), dequeue(), front(), and isEmpty() methods.

Note: This implementation is a basic implementation of queue data structure, and it might not be efficient for handling a large number of elements. In such cases, other data structures like Linked List or Doubly Linked List could be used instead of Array.

related categories

gistlibby LogSnag