Create Tree Challenge (recursive)

Create a tree from a list of paths

by Aubrey Taylor

JavaScript

function recursePathComponents(parts, context) {
    var key, leaf;
    key = parts.shift();
    
    if(key) {
        leaf = context[key] = context[key] || {};
        recursePathComponents(parts, leaf);
    }
}

function createTree(list) {
    var output;
    output = {};
    
    _.each(list, function(el, i, items){
        recursePathComponents(el.split('/'), output);
    });
    
    return output;
}

var list =  ['path/to/file', 'foo/bar/baz', 'foo/zap/zip', 'joe'];

console.log(createTree(list));