recursion practice - append nodes to object

// giving an empty object and a list,
// return the object append the node by sequence in the list

var nodeList = ["a", "b", "c"];
var obj = {};

// output {a:{b:{c:{}}}}

var genereteNode = (nodeList)=>{
    
   obj = _process(obj, nodeList) 
}

// recursion 
var _process = (obj, nodeList)=>{
    // base conditions
    if(nodeList.length == 0) return;

    if(nodeList.length === 1){

        var node = nodeList[0];
        
        obj[node] = {};
        
        return;
    }

    var nodeShifted = nodeList.shift();
    
    // general solution
    obj[nodeShifted] = {};
    
    // reduce function
    _process(obj[nodeShifted], nodeList)

    //console.log(obj);
    return obj;
}

genereteNode(nodeList);

console.log(obj);

你可能感兴趣的:(recursion practice - append nodes to object)