Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Last active July 31, 2016 17:38
Show Gist options
  • Save khaled0fares/c2bb6ea1e616a6df7268b2c51966772a to your computer and use it in GitHub Desktop.
Save khaled0fares/c2bb6ea1e616a6df7268b2c51966772a to your computer and use it in GitHub Desktop.
Queue implemented in JS
let Queue = function(){
this.Store = [];
}
Queue.prototype.enqueue = function(ele){
this.Store.push(ele);
}
Queue.prototype.dequeue = function(){
if(this.empty()){
throw new Error("Queue is empty, you can't run the dequeue operation");
}
return this.Store.shift();
}
Queue.prototype.clear = function(){
this.Store = [];
return true;
}
Queue.prototype.empty = function(){
if(this.Store.length == 0){
return true;
}
return false;
}
Queue.prototype.toString = function(){
let i = 0,
len = this.Store.length,
string = "";
for(i; i < len; i++){
string += this.Store[i] + "\n"
}
return string
}
Queue.prototype.front = function(){
if(this.empty()){
throw new Error("Queue is empty");
}
return this.Store[0];
}
Queue.prototype.back = function(){
if(this.empty()){
throw new Error("Queue is empty");
}
let len = this.Store.length, last = len - 1;
return this.Store[last];
}
//============Using ES6 syntax============
class Queue {
constructor(){
this.Store = [];
}
enqueue (ele){
this.Store.push(ele);
}
dequeue(){
if(this.empty()){
throw new Error("Queue is empty, you can't run the dequeue operation");
}
return this.Store.shift();
}
clear(){
this.Store = [];
return true;
}
empty(){
if(this.Store.length == 0){
return true;
}
return false;
}
toString(){
let i = 0,
len = this.Store.length,
string = "";
for(i; i < len; i++){
string += this.Store[i] + "\n"
}
return string
}
front(){
if(this.empty()){
throw new Error("Queue is empty");
}
return this.Store[0];
}
back(){
if(this.empty()){
throw new Error("Queue is empty");
}
let len = this.Store.length, last = len - 1;
return this.Store[last];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment