Skip to content

Instantly share code, notes, and snippets.

@imsarvesh
Last active January 19, 2019 05:07
Show Gist options
  • Save imsarvesh/d2892073a499cd359482788a4cdba944 to your computer and use it in GitHub Desktop.
Save imsarvesh/d2892073a499cd359482788a4cdba944 to your computer and use it in GitHub Desktop.
Priority Queue JavaScript Data Structure
//Queue Data Structure
function createQueue(){
const q = [];
return {
//enque
enque(item){
return q.push(item);
},
//deque
deque(item){
return q.shift();
},
//peek
peek(){
return q[0];
},
//length
get length(){
return q.length;
},
//isEmpty
isEmpty(){
return q.length === 0
}
}
}
function createPriorityQueue(){
const lowPriorityQueue = createQueue()
const highPriorityQueue = createQueue()
return {
//enque
enque(item, highPriority = false){
highPriority ? highPriorityQueue.enque(item) : lowPriorityQueue.enque(item)
return item;
},
//deque
deque(){
if(!highPriorityQueue.isEmpty()){
return highPriorityQueue.deque()
}
return lowPriorityQueue.deque();
},
//peek
peek(){
if(!highPriorityQueue.isEmpty()){
return highPriorityQueue.peek()
}
return lowPriorityQueue.peek();
},
//length
get length(){
return highPriorityQueue.length + lowPriorityQueue.length;
},
//isEmpty
isEmpty(){
return highPriorityQueue.isEmpty() && lowPriorityQueue.isEmpty()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment