/

JavaScript Data Structures: Queue - An Introduction

JavaScript Data Structures: Queue - An Introduction

In JavaScript, queues are similar to stacks but with a different way of handling data insertion and removal. They follow the First In, First Out (FIFO) principle, meaning that the first item to be added is the first one to be removed. Just like waiting in line at a restaurant, a disco, or a concert hall, items are processed in the order they were added.

To implement a queue in JavaScript, we can use an array as the internal storage and utilize private class fields for encapsulation. Here’s an example implementation:

1
2
3
4
5
6
7
8
9
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
}

To use this queue, first create a new object from the Queue class and then call its methods. The enqueue() method adds items to the queue, while the dequeue() method retrieves and removes an item.

Example usage:

1
2
3
4
5
6
7
8
9
10
11
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

Queues are handy data structures in JavaScript for scenarios where you need to manage and process items in a specific order, such as task scheduling, event handling, or algorithmic problems.

tags: [“JavaScript”, “data structures”, “queue”]