This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
24. create a Priority Queue in JavaScript
Here is a possible solution for the Priority Queue in JavaScript:
class PriorityQueue { constructor(compare) { this.queue = []; this.compare = compare; } add(element) { this.queue.push(element); this.queue.sort(this.compare); } poll() { return this.queue.shift(); } peek() { return this.queue[0]; } size() { return this.queue.length; }}
Explanation:
- The Priority Queue constructor takes a
compare
function that defines the order in which the elements should be sorted. - The
add
method adds a new element to the queue and sorts it based on thecompare
function. - The
poll
method removes and returns the head element of the queue. - The
peek
method returns the head element without removing it. - The
size
method returns the amount of items in the queue.
Note that, depending on the use case, there might be more efficient ways to implement a Priority Queue in JavaScript, such as using a heap instead of sorting the whole array every time a new element is added.