将多个全路径转换为树路径的算法 - An algorithm that convert multi full path to path tree

I got a problem to convert multiple full path to a path tree, like this:

/* source: 
 /a/b/c/d/e
 /a/b/e/f/g
 /a/b/h
 /a/i/j
 /a/i/k
 
   what I need:
        
         a
       /   \
      b     i
     /|\   / \
    c e h j   k
    | |
    d f
    | |
    e g
*/

So I have to scan each full-path to generate this tree structure, here is my code with JavaScript:

let rtree = [];
array.map((item) =>{
    let {key,title}=item;             // key is the full path
    let uri=key.split('/');           // split the full path with '/'
    let uri_pt = rtree;
    let path='';
    if(uri_pt.length==0){
        let root={
            key:path+'/'+uri[1],
            title:uri[1],
        }
        if(uri.length>2){
            root.children=[];
        }
        uri_pt.push(root);
    }
    for (let i in uri){
        if(i==0) continue;
        path+='/'+uri[i];
        let treeitem = {
            key:path,
            title:uri[i]
        }
        if(i!=uri.length-1){
            treeitem.children=[];
        }
        if(uri_pt.length==0){
            uri_pt.push(treeitem);
        }
        let isExist=false;
        for(let j in uri_pt){
            if(uri_pt[j].key==treeitem.key){
                if(i!=uri.length-1 && !uri_pt[j].children){
                    uri_pt[j].children=[];
                }
                uri_pt=(i==uri.length-1?uri_pt:uri_pt[j].children);
                isExist=true;
                break;
            }
        }
        if (!isExist){
            uri_pt.push(treeitem);
            if(i!=uri.length-1 && !uri_pt[uri_pt.length-1].children){
                uri_pt[uri_pt.length-1].children=[];
            }
            uri_pt=(i==uri.length-1?uri_pt:uri_pt[uri_pt.length-1].children);
        }
    }
})

It's a totally inefficiency algorithm, but worked, if any improvement, please let me know.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值