Skip to content

Instantly share code, notes, and snippets.

@joelbarbosa
Last active December 4, 2018 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelbarbosa/9d2f67d84fbe5218f724ccdd07b500e5 to your computer and use it in GitHub Desktop.
Save joelbarbosa/9d2f67d84fbe5218f724ccdd07b500e5 to your computer and use it in GitHub Desktop.
import { createQueue } from './queueu';
function createPriorityQueue() {
const lowPriorityQueue = createQueue();
const highPriorityQueue = createQueue();
return {
enqueue(item, isHighPriority = false) {
isHighPriority
? highPriorityQueue.enqueue(item)
: lowPriorityQueue.enqueue(item);
},
dequeue() {
if(!highPriorityQueue.isEmpty()) {
return highPriorityQueue.dequeue();
}
return lowPriorityQueue.dequeue();
},
peek() {
if(!highPriorityQueue.isEmpty()) {
return highPriorityQueue.peek();
}
return lowPriorityQueue.peek();
},
get length() {
return highPriorityQueue.length +
lowPriorityQueue.length;
},
isEmpty() {
return highPriorityQueue.isEmpty() &&
lowPriorityQueue.isEmpty();
}
}
}
const q = createPriorityQueue();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
console.log(q.peek())
q.dequeue();
q.dequeue();
console.log(q.peek())
console.log(q.length)
q.enqueue(5, true);
console.log(q.peek())
console.log(q.length)
q.enqueue(6);
console.log(q.peek())
q.dequeue();
console.log(q.peek())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment