DEV Community

Ivy-Walobwa
Ivy-Walobwa

Posted on

Queue: Array as Storage

Implementing a queue using arrays in JavaScript is quite simple.
You use the push() and shift() methods provided for Arrays.

Implementation

1.Create queue class

class Queue{ constructor() { this.items = []; } //add methods } 
Enter fullscreen mode Exit fullscreen mode

We create an items array to store our data

2.Add methods to class

We'll implement the enqueue, dequeue and peek operation on queues.

Enqueue

 enqueue(data) { //add data to end of queue this.items.push(data); } 
Enter fullscreen mode Exit fullscreen mode

The push method on arrays, adds data to end of queue.

Dequeue

 dequeue() { //if empty do nothing else remove first item if (this.items.length === 0) { return; } //return this.items.shift() this.items.shift() } 
Enter fullscreen mode Exit fullscreen mode

The shift() method removes the first item in queue and returns it.

Peek

 peek() { //if not empty return first item if (this.items.length === 0) { return "Empty queue"; } return this.items[0]; } 
Enter fullscreen mode Exit fullscreen mode

This returns the first item in queue.

Pretty straightforward.

Top comments (0)