一道算法题,有会的可以一起讨论下

const data = {

    name: 'A',
    child: [{
            name: 'AB',
            child: [{
                    name: 'AABA'
                },
                {
                    name: 'AABB'
                }
            ]
        },
        {
            name: 'AC',
            child: [{
                    name: 'AACA'
                },
                {
                    name: 'AACB'
                }
            ]
        }
    ]
}
// 请自行封装一个findPath的函数,实现如下效果
// 调用示例

findPath('AABB'); //["A", "AB", "AABB"]

findPath('AABA'); //["A", "AB", "AABA"]

findPath('AACB'); //["A", "AC", "AACB"]

findPath('AC'); //["A", "AC"]

findPath('AACA'); //["A", "AC", "AACA"]

阅读 656
评论
    4 个回答
    • 2.5k
    const data = {
            name: 'A',
            child: [{
                name: 'AB',
                child: [{
                    name: 'AABA'
                },
                    {
                        name: 'AABB'
                    }
                ]
            },
                {
                    name: 'AC',
                    child: [{
                        name: 'AACA'
                    },
                        {
                            name: 'AACB'
                        }
                    ]
                }
            ]
        }
        function getAllKeys(data,result=[]){
            result.push(data.name);
            if(data.child){
                for(let c of data.child){
                    getAllKeys(c,result);
                }
            }
            return result;
        }
        const result=getAllKeys(data);
        function findPath(path){
            return result.filter(item=>path.indexOf(item)!=-1);
        }
        function wraplog(fun){
            return function addParams(...params){
                const _r=fun(...params);
                console.log(_r);
                return _r;
            }
        }
        const _findPath=wraplog(findPath);
        _findPath('AABB'); //["A", "AB", "AABB"]
    
        _findPath('AABA'); //["A", "AB", "AABA"]
    
        _findPath('AACB'); //["A", "AC", "AACB"]
    
        _findPath('AC'); //["A", "AC"]
    
        _findPath('AACA'); //["A", "AC", "AACA"]