JavaScript data structure: queue

The queue is similar to the stack, except that the insertion point is different from the removal point.

We add at one end of the queue and then delete from the other end.

This time, we will call it First In First Out (FIFO).

Just like any queue you can think of, such as in a restaurant, disco, or while waiting to enter a concert hall.

This is a possible implementation of the queue in JavaScript using the following commandPrivate class area, Using an array as internal storage:

class Queue {
  #items = []
  enqueue = (item) => this.#items.splice(0, 0, item)
  dequeue = () => this.#items.pop()
  isempty = () => this.#items.length === 0
  empty = () => (this.#items.length = 0)
  size = () => this.#items.length
}

The method of use is as follows: first initialize an object from the class, and then call its method:

  • enqueue()Add item
  • dequeue()Remove items from the queue

example:

const queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.size() //3

queue.dequeue() //1
queue.dequeue() //2
queue.dequeue() //3

Download mine for freeJavaScript beginner's manual


More js tutorials: