Binary Heap Priority Queue

Implement a binary heap priority queue with push pop and peek supporting custom comparators for scheduling.

JavascriptData Integrity

Code

javascriptsnippet
1 line
export function priorityQueue(cmp=(a,b)=>a-b){const heap=[];function siftUp(i){while(i>0){const p=(i-1)>>1;if(cmp(heap[i],heap[p])<0){[heap[i],heap[p]]=[heap[p],heap[i]];i=p;}else break;}}function siftDown(i){const n=heap.length;while(true){let s=i,l=2*i+1,r=2*i+2;if(l<n&&cmp(heap[l],heap[s])<0)s=l;if(r<n&&cmp(heap[r],heap[s])<0)s=r;if(s!==i){[heap[i],heap[s]]=[heap[s],heap[i]];i=s;}else break;}}return{push(v){heap.push(v);siftUp(heap.length-1);},pop(){if(heap.length===0)return undefined;const top=heap[0];const last=heap.pop();if(heap.length>0){heap[0]=last;siftDown(0);}return top;},peek:()=>heap[0],size:()=>heap.length};}

How it works

Count the functions p, priorityQueue, siftUp and siftDown as the entire surface area of Binary Heap Priority Queue.

What to watch for

  • The guard heap.length===0 short-circuits the flow with an early return when its condition holds.

Putting it to use

The main signature reads export function priorityQueue(cmp=(a,b)

priorityQueue is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `p`, `priorityQueue`, `siftUp` at load time.