UNPKG

heapify

Version:
1 lines 2.19 kB
var t,e={};t=e,Object.defineProperty(t,"X",{value:!0}),t.m=void 0,t.m=class{constructor(t=64,e=[],i=[],s=Uint32Array,h=Uint32Array){if(this._capacity=t,this._keys=new s(t+1),this._priorities=new h(t+1),this._hasPoppedElement=!1,e.length!==i.length)throw new Error("Number of keys does not match number of priorities provided.");if(t<e.length)throw new Error("Capacity less than number of provided keys.");for(let t=0;t<e.length;t++)this._keys[t+1]=e[t],this._priorities[t+1]=i[t];this.length=e.length;for(let t=e.length>>>1;t>=1;t--)this.bubbleDown(t)}get capacity(){return this._capacity}clear(){this.length=0,this._hasPoppedElement=!1}bubbleUp(t){const e=this._keys[t],i=this._priorities[t];for(;t>1;){const e=t>>>1;if(this._priorities[e]<=i)break;this._keys[t]=this._keys[e],this._priorities[t]=this._priorities[e],t=e}this._keys[t]=e,this._priorities[t]=i}bubbleDown(t){const e=this._keys[t],i=this._priorities[t],s=1+(this.length>>>1),h=this.length+1;for(;t<s;){const e=t<<1;let s=this._priorities[e],r=this._keys[e],o=e;const n=e+1;if(n<h){const t=this._priorities[n];t<s&&(s=t,r=this._keys[n],o=n)}if(s>=i)break;this._keys[t]=r,this._priorities[t]=s,t=o}this._keys[t]=e,this._priorities[t]=i}push(t,e){if(this.length===this._capacity)throw new Error("Heap has reached capacity, can't push new items");if(this._hasPoppedElement)this._keys[1]=t,this._priorities[1]=e,this.length++,this.bubbleDown(1),this._hasPoppedElement=!1;else{const i=this.length+1;this._keys[i]=t,this._priorities[i]=e,this.length++,this.bubbleUp(i)}}pop(){if(0!==this.length)return this.removePoppedElement(),this.length--,this._hasPoppedElement=!0,this._keys[1]}peekPriority(){return this.removePoppedElement(),this._priorities[1]}peek(){return this.removePoppedElement(),this._keys[1]}removePoppedElement(){this._hasPoppedElement&&(this._keys[1]=this._keys[this.length+1],this._priorities[1]=this._priorities[this.length+1],this.bubbleDown(1),this._hasPoppedElement=!1)}get size(){return this.length}dumpRawPriorities(){this.removePoppedElement();const t=Array(this.length-1);for(let e=0;e<this.length;e++)t[e]=this._priorities[e+1];return`[${t.join(" ")}]`}};var i=e.m,s=e.X;export{i as MinQueue,s as __esModule};