@utopia-utils/tree
Version:
Collection of common tree utils
2 lines • 2.03 kB
JavaScript
import{isFunction as e}from"@utopia-utils/share";const t={id:`id`,children:`children`,parentId:`parentId`};function n(n,r,i){if(!e(r))throw Error(`traverse action should be a function`);let{fieldNames:a}=i||{},{children:o}={...t,...a},s=Array.isArray(n)?[...n]:[n];for(;s.length;){let e=s.shift();if(e){if(r(e)===!1)break;e[o]&&s.push(...e[o])}}}function r(e,n){let{listFieldNames:r,treeFieldNames:i}=n||{},{id:a,parentId:o}={...t,...r},{id:s,parentId:c,children:l}={...t,...i},u=new Map,d=[];return e.forEach(e=>{i&&(e[s]=e[a],e[c]=e[o]),e[l]=[],u.set(e[a],e)}),e.forEach(e=>{let t=u.get(e[o]);t?t[l].push(e):d.push(e)}),d}function i(n,r,i){if(!e(r))throw Error(`traverse action should be a function`);let{fieldNames:a,order:o=`pre`}=i||{},{children:s}={...t,...a},c=(e,t,n)=>{for(let i of e){if(o===`pre`&&r(i,t,n)===!1)return!1;if(i[s]){let e=c(i[s],i,n+1);if(e===!1)return!1}if(o===`post`&&r(i,t,n)===!1)return!1}};c(Array.isArray(n)?n:[n],null,0)}function a(e,n){let{fieldNames:r,onEachTraverse:i}=n||{},{children:a}={...t,...r},o=Array.isArray(e)?[...e]:[e];for(let e=0;e<o.length;e++){let t=o[e];i?.(t),t[a]&&o.splice(e+1,0,...t[a])}return o}function o(e,n,r){let{fieldNames:i,onEachTraverse:a}=r||{},{children:o}={...t,...i},s=Array.isArray(e)?[...e]:[e];function c(e){let t=e.map(e=>({...e}));return t.filter(e=>(e[o]&&(e[o]=c(e[o])),a?.(e),n(e)||!!e[o]?.length))}return c(s)}function s(t,r,i){let{isFindAll:a,fieldNames:o,onEachTraverse:s}=i||{};if(!e(r))throw Error(`predicate should be a function`);let c=[];return n(t,e=>{if(s?.(e),r(e)&&(c.push(e),!a))return!1},{fieldNames:o}),c}function c(e,n,r){let{fieldNames:i}=r||{},{children:a}={...t,...i},o=[],s=Array.isArray(e)?[...e]:[e],c=new Set;for(;s.length;){let e=s[0];if(c.has(e))o.pop(),s.shift();else if(c.add(e),e[a]&&s.unshift(...e[a]),o.push(e),n(e))return o}return null}export{n as breadthFirstTraverse,r as buildTreeFromList,i as deepFirstTraverse,a as flattenTree,o as treeFilterNode,s as treeFindNode,c as treeFindPath};
//# sourceMappingURL=index.mjs.map