Binary Heap Priority Queue
Implement a binary heap priority queue with push pop and peek supporting custom comparators for scheduling.
Code
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===0short-circuits the flow with an earlyreturnwhen 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
Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.IEEE 754 ConverterConvert decimal floats to and from IEEE 754 single- and double-precision bit patterns in hex and binary.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.