@dqcai/tree
Version:
A TypeScript library for converting arrays to tree structures and vice versa
3 lines (2 loc) • 1.69 kB
JavaScript
class _{constructor(){this.myId=0}array2Tree(i,n,t,r=null,o=1){const s=o,c=i.filter(e=>e[t]===r||r==null&&e[t]==null||r==null&&e[t]==null||r==null&&e[t]=="");if(c&&c.length>0)return c.forEach(e=>{e.$level=s,e.$children=this.array2Tree(i,n,t,e[n],s+1)||[]}),c;{const e=i.find(d=>d[n]===r);e&&(e.$is_leaf=1);return}}array2SortByTree(i,n,t,r=null,o=1,s=[],c){const e=s,d=o;if(i&&i.length>=e.length&&n&&t){const a=i.filter(u=>u[t]===r||r==null&&u[t]==null||r==null&&u[t]==null||r==null&&u[t]=="");if(a&&a.length>0)a.forEach((u,$)=>{const l=u;l.$level=d,l.$index=$+1,l.$tree_index=(c?c+".":"")+l.$index,e.push(l),this.array2SortByTree(i,n,t,u[n],d+1,e,l.$tree_index)});else{const u=e.find($=>$[n]===r);u&&(u.$is_leaf=1)}}return e}array2SortAndWeight(i,n,t,r,o=null,s=1,c=1,e=[],d){const a=e,u=s;if(i&&i.length>=a.length){const $=i.filter(l=>l[t]===o||o==null&&l[t]==null||o==null&&l[t]==null);if($&&$.length>0){const l=$.reduce((f,g)=>f+(g[r]||0),0);$.forEach((f,g)=>{const h=f;h.$sum_weight=l,h.$weight_percent=(f[r]||0)/l,h.$parent_weight_percent=c,h.$root_weight_percent=h.$parent_weight_percent*h.$weight_percent,h.$level=u,h.$index=g+1,h.$tree_index=(d?d+".":"")+h.$index,a.push(h),this.array2SortAndWeight(i,n,t,r,f[n],u+1,h.$root_weight_percent,a,h.$tree_index)})}else{const l=a.find(f=>f[n]===o);l&&(l.$is_leaf=1)}}return a}tree2Array(i,n,t=null,r=1){const o=r;let s=[];return i.forEach(c=>{const e=Object.assign({},c);if(e.$id=++this.myId,e.$parent_id=t,s.push(e),c[n]){const d=JSON.parse(JSON.stringify(c[n]));delete e[n];const a=this.tree2Array(d,n,this.myId,o+1);s=s.concat(a)}}),s}resetIdCounter(){this.myId=0}}export{_ as Array2Tree,_ as default};
//# sourceMappingURL=index.mjs.map