Last active
December 18, 2019 11:43
-
-
Save guilhermepontes/005e93cb6d7bd7459c71a3a01e3159b2 to your computer and use it in GitHub Desktop.
queue data structure, 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
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() | |
) | |
} | |
} | |
} |
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
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