Skip to content

Instantly share code, notes, and snippets.

@negarjf
Last active August 4, 2019 05:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save negarjf/71df22e38eed3959fbf4f48a4dcf429f to your computer and use it in GitHub Desktop.
Save negarjf/71df22e38eed3959fbf4f48a4dcf429f to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/dafobir
class circularQueue{
constructor(max){
this.array = [];
this.max= max;
this.length = 0;
this.front = 0;
this.end = 0;
for(let i = 0; i < this.max; i++){
this.array[i] = null;
}
}
get isFull(){
return this.length === this.max;
}
get isEmpty(){
return this.length === 0;
}
get peek(){
return this.array[this.front];
}
add(item) {
if(!this.isFull){
this.array[this.end] = item;
this.length++;
this.end = (this.end + 1)% this.max;
}else{
console.error('Queue is full.');
}
this.log();
}
remove(){
if(!this.isEmpty){
this.array[this.front] = null;
this.length--;
this.front = (this.front + 1)% this.max;
}else{
console.error('Queue is empty.');
}
this.log();
}
log(){
console.log('length is: ' + this.length);
console.log('front is: ' + this.front);
console.log('end is: ' + this.end);
console.log('Peek: ' + this.peek);
console.log(this.array);
}
}
// Create a circular queue of length 3
let numbers = new circularQueue(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment