-
Notifications
You must be signed in to change notification settings - Fork 39
/
arrayToTree.min.js
1 lines (1 loc) · 2.21 KB
/
arrayToTree.min.js
1
"use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var r,t=1,n=arguments.length;t<n;t++)for(var o in r=arguments[t])Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o]);return e}).apply(this,arguments)},defaultConfig=(Object.defineProperty(exports,"__esModule",{value:!0}),{id:"id",parentId:"parentId",dataField:"data",childrenField:"children",throwIfOrphans:!1,rootParentIds:{"":!(exports.countNodes=exports.arrayToTree=void 0)},nestedIds:!0,assign:!1});function arrayToTree(c,e){void 0===e&&(e={});for(var r,t=__assign(__assign({},defaultConfig),e),n=[],o={},a=t.throwIfOrphans?new Set:null,s=0,h=c;s<h.length;s++){var i=h[s],d=t.nestedIds?getNestedProperty(i,t.id):i[t.id],l=t.nestedIds?getNestedProperty(i,t.parentId):i[t.parentId];if(t.rootParentIds[d])throw new Error("The item array contains a node whose parentId both exists in another node and is in "+'`rootParentIds` (`itemId`: "'.concat(d,'", `rootParentIds`: ').concat(Object.keys(t.rootParentIds).map(function(e){return'"'.concat(e,'"')}).join(", "),")."));Object.prototype.hasOwnProperty.call(o,d)||(o[d]=((r={})[t.childrenField]=[],r)),a&&a.delete(d),t.dataField?o[d][t.dataField]=i:t.assign?o[d]=Object.assign(i,((r={})[t.childrenField]=o[d][t.childrenField],r)):o[d]=__assign(__assign({},i),((i={})[t.childrenField]=o[d][t.childrenField],i));i=o[d];null==l||t.rootParentIds[l]?n.push(i):(Object.prototype.hasOwnProperty.call(o,l)||(o[l]=((d={})[t.childrenField]=[],d),a&&a.add(l)),o[l][t.childrenField].push(i))}if(null!=a&&a.size)throw new Error("The items array contains orphans that point to the following parentIds: "+"[".concat(Array.from(a),"]. These parentIds do not exist in the items array. Hint: prevent orphans to result ")+"in an error by passing the following option: { throwIfOrphans: false }");if(t.throwIfOrphans&&countNodes(n,t.childrenField)<Object.keys(o).length)throw new Error("The items array contains nodes with a circular parent/child relationship.");return n}function countNodes(e,t){return e.reduce(function(e,r){return e+1+(r[t]&&countNodes(r[t],t))},0)}function getNestedProperty(e,r){return r.split(".").reduce(function(e,r){return e&&e[r]},e)}exports.arrayToTree=arrayToTree,exports.countNodes=countNodes;