@safs.io/match
Version:
Gale/Shapely deferred acceptance algorithm
2 lines (1 loc) • 2.06 kB
JavaScript
var c=class{constructor(t){this._rankedCounterparts=[];this._id=t.id,this._sourceObject=t}get id(){return this._id}get rankedCounterparts(){return this._rankedCounterparts}set rankedCounterparts(t){this._rankedCounterparts=t}get sourceObject(){return this._sourceObject}};function s(i){return i.reduce((t,e)=>(e.acceptedCounterparts.forEach(r=>{t.push({left:r,right:e})}),t),[])}function u({leftEls:i,rightEls:t}){for(;i.length;){let e=i.shift();if(typeof e=="undefined")break;let{rankedCounterparts:r}=e;for(;r.length;){let a=r.shift();if(a==null?void 0:a.willAcceptCounterpart(e)){let n=a.acceptCounterpart(e);n&&i.unshift(n);break}}}return s(t)}var o=class{constructor(t){this._rankedCounterparts=[];this._acceptedCounterparts=[];this._rankTable={};this._id=t.id,this._capacity=t.capacity,this._sourceObject=t}get id(){return this._id}get acceptedCounterparts(){return this._acceptedCounterparts}get lastAcceptedCounterpart(){return this.acceptedCounterparts[this.acceptedCounterparts.length-1]}get atOrOverCapacity(){return this.acceptedCounterparts.length>=this._capacity}get rankedCounterparts(){return this._rankedCounterparts}set rankedCounterparts(t){this._rankTable=t.reduce((e,{id:r},a)=>(e[r]=a,e),{}),this._rankedCounterparts=t}get sourceObject(){return this._sourceObject}removeLastAcceptedCounterpart(){return this._acceptedCounterparts.pop()}acceptCounterpart(t){let e=this.atOrOverCapacity?this.removeLastAcceptedCounterpart():null;if(this.acceptedCounterparts.length===0||this.isRankedBetterThan(this.lastAcceptedCounterpart,t))this._acceptedCounterparts.push(t);else for(let[r,a]of this.acceptedCounterparts.entries())if(this.isRankedBetterThan(t,a)){this._acceptedCounterparts.splice(r,0,t);break}return e}isRankedBetterThan(t,e){var n;let r=this._rankTable[t.id]||-1,a=((n=this._rankTable)==null?void 0:n[e==null?void 0:e.id])||-1;return r<a}willAcceptCounterpart(t){return this._rankTable.hasOwnProperty(t.id)&&(!this.atOrOverCapacity||this.isRankedBetterThan(t,this.lastAcceptedCounterpart))}};export{c as LeftEl,o as RightEl,u as match};