Skip to content

Instantly share code, notes, and snippets.

@guilhermepontes
Last active December 18, 2019 11:43
Show Gist options
  • Save guilhermepontes/005e93cb6d7bd7459c71a3a01e3159b2 to your computer and use it in GitHub Desktop.
Save guilhermepontes/005e93cb6d7bd7459c71a3a01e3159b2 to your computer and use it in GitHub Desktop.
queue data structure, javascript
function createPriorityQueue() {
const highPriorityQueue = createQueue()
const lowPriorityQueue = createQueue()
return {
enqueue(item, isHighPriority = false) {
(isHighPriority
? highPriorityQueue
: lowPriorityQueue
).enqueue(item)
},
dequeue() {
return (!highPriorityQueue.isEmpty()
? highPriorityQueue
: lowPriorityQueue
).dequeue()
},
peek() {
return (!highPriorityQueue.isEmpty()
? highPriorityQueue
: lowPriorityQueue
).peek()
},
get length() {
return (
highPriorityQueue.length + lowPriorityQueue.length
)
},
isEmpty() {
return (
highPriorityQueue.isEmpty() && lowPriorityQueue.isEmpty()
)
}
}
}
function createQueue() {
const queue = []
return {
enqueue(item) {
queue.unshift(item)
},
dequeue() {
return queue.pop()
},
peek() {
return queue[queue.length - 1]
},
get length() {
return queue.length
},
isEmpty() {
return queue.length === 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment