Created
December 5, 2018 20:26
-
-
Save shadowcodex/6e9c377493d189117d78e5e8ac2a4fea to your computer and use it in GitHub Desktop.
Priority Queue in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Queue { | |
constructor () { | |
this.priority = []; | |
this.regular = []; | |
} | |
enqueue(item, high = false) { | |
if(high) { | |
this.priority.unshift(item); | |
} else { | |
this.regular.unshift(item); | |
} | |
return(item); | |
} | |
dequeue(){ | |
if(this.priority.length > 0) { | |
return this.priority.pop(); | |
} | |
if(this.regular.length > 0) { | |
return this.regular.pop(); | |
} else { | |
return null; | |
} | |
} | |
peak() { | |
if(this.priority.length > 0) { | |
return this.priority[this.priority.length - 1]; | |
} | |
if(this.regular.length > 0) { | |
return this.regular[this.regular.length - 1]; | |
} else { | |
return null; | |
} | |
} | |
get length() { | |
return this.priority.length + this.regular.length; | |
} | |
} | |
let queue = new Queue(); | |
console.log("length", queue.length); | |
console.log("enqueue", queue.enqueue("hello world...")); | |
console.log("length", queue.length); | |
console.log("peak", queue.peak()); | |
console.log("enequeue", queue.enqueue("I'm important", true)); | |
console.log("length", queue.length); | |
console.log("peak", queue.peak()); | |
console.log("enqueue", queue.enqueue("another regular task")); | |
console.log("peak", queue.peak()); | |
console.log("dequeue", queue.dequeue()); | |
console.log("peak", queue.peak()); | |
console.log("dequeue", queue.dequeue()); | |
console.log("peak", queue.peak()); | |
console.log("dequeue", queue.dequeue()); | |
console.log("peak", queue.peak()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment