DEV Community

loading...

Queue: Array as Storage

ivywalobwa profile image Ivy-Walobwa ・1 min read

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
}

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);
    }

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()
    }

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];
    }

This returns the first item in queue.

Pretty straightforward.

Discussion (0)

pic
Editor guide