UNPKG

decentralized-internet

Version:

An NPM library of programs to create decentralized web and distributed computing projects

1 lines 2.58 kB
"use strict";const Hoek=require("hoek"),internals={};exports=module.exports=internals.Topo=function(){this._items=[],this.nodes=[]},internals.Topo.prototype.add=function(t,e){const s=[].concat((e=e||{}).before||[]),o=[].concat(e.after||[]),n=e.group||"?",r=e.sort||0;Hoek.assert(-1===s.indexOf(n),"Item cannot come before itself:",n),Hoek.assert(-1===s.indexOf("?"),"Item cannot come before unassociated items"),Hoek.assert(-1===o.indexOf(n),"Item cannot come after itself:",n),Hoek.assert(-1===o.indexOf("?"),"Item cannot come after unassociated items"),[].concat(t).forEach((t,e)=>{const i={seq:this._items.length,sort:r,before:s,after:o,group:n,node:t};this._items.push(i)});const i=this._sort();return Hoek.assert(!i,"item","?"!==n?"added into group "+n:"","created a dependencies error"),this.nodes},internals.Topo.prototype.merge=function(t){t=[].concat(t);for(let e=0;e<t.length;++e){const s=t[e];if(s)for(let t=0;t<s._items.length;++t){const e=Hoek.shallow(s._items[t]);this._items.push(e)}}this._items.sort(internals.mergeSort);for(let t=0;t<this._items.length;++t)this._items[t].seq=t;const e=this._sort();return Hoek.assert(!e,"merge created a dependencies error"),this.nodes},internals.mergeSort=function(t,e){return t.sort===e.sort?0:t.sort<e.sort?-1:1},internals.Topo.prototype._sort=function(){const t={},e=Object.create(null),s=Object.create(null);for(let o=0;o<this._items.length;++o){const n=this._items[o],r=n.seq,i=n.group;s[i]=s[i]||[],s[i].push(r),t[r]=n.before;const c=n.after;for(let t=0;t<c.length;++t)e[c[t]]=(e[c[t]]||[]).concat(r)}let o=Object.keys(t);for(let e=0;e<o.length;++e){const n=o[e],r=[],i=Object.keys(t[n]);for(let e=0;e<i.length;++e){const o=t[n][i[e]];s[o]=s[o]||[];for(let t=0;t<s[o].length;++t)r.push(s[o][t])}t[n]=r}const n=Object.keys(e);for(let o=0;o<n.length;++o){const r=n[o];if(s[r])for(let o=0;o<s[r].length;++o){const n=s[r][o];t[n]=t[n].concat(e[r])}}let r;const i={};o=Object.keys(t);for(let e=0;e<o.length;++e){const s=o[e];r=t[s];for(let t=0;t<r.length;++t)i[r[t]]=(i[r[t]]||[]).concat(s)}const c={},l=[];for(let t=0;t<this._items.length;++t){let e=t;if(i[t]){e=null;for(let t=0;t<this._items.length;++t){if(!0===c[t])continue;i[t]||(i[t]=[]);const s=i[t].length;let o=0;for(let e=0;e<s;++e)l.indexOf(i[t][e])>=0&&++o;if(o===s){e=t;break}}}null!==e&&(c[e=e.toString()]=!0,l.push(e))}if(l.length!==this._items.length)return new Error("Invalid dependencies");const h={};for(let t=0;t<this._items.length;++t){const e=this._items[t];h[e.seq]=e}const a=[];this._items=l.map(t=>{const e=h[t];return a.push(e.node),e}),this.nodes=a};