DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Creating a Queue in JS

  1. Queue data structure can be thought of as a container where records enter on one end and exit on the other
  2. Process of adding something to queue is something called 'Enqueuing or adding' , removing something from a queue is also called 'Dequeuing'
  3. Queue follows First In First Out principal

Before we go ahead and write a Queue we should understand the following concepts in JS

  1. Unshift method, adds something in front of the JS array
  2. Pop method , removes something from the end of the JS array

So the Queue basically limits access to so many options like shift, unshift, push, splice and slice in JS and only allows shift and pop.

class Queue{
constructor(){
this.data=[];
}
add(record){
this.data.unshift(record)
}
remove(){
return this.data.pop()
}
peek(){
// console.log()
let lastElement=this.data[this.data.length-1]
return lastElement;
}
}
const q1 = new Queue();
const q2 = new Queue();`
view raw Queue.js hosted with ❤ by GitHub

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️