Skip to content

Instantly share code, notes, and snippets.

@naholyr
Created November 24, 2014 11:06
Show Gist options
  • Save naholyr/b6e38108d13a1ed41b19 to your computer and use it in GitHub Desktop.
Save naholyr/b6e38108d13a1ed41b19 to your computer and use it in GitHub Desktop.
console.log(JSON.stringify(pathsToTree([
"a/b",
"a/c/d",
"e"
]), null, " "));
/*
{
"e": null,
"a": {
"b": null,
"c": {
"d": null
}
}
}
*/
function pathsToTree (paths) {
return paths.slice().sort(compareLengthAsc).map(pathToTree).reduce(merge);
}
function compareLengthAsc (p1, p2) {
return p1.length - p2.length;
}
function pathToTree (path) {
if (!path) {
return null;
}
var i = path.indexOf("/");
var nodeName = (i === -1) ? path : path.substring(0, i);
var childPath = (i === -1) ? "" : path.substring(i + 1);
var result = {};
result[nodeName] = pathToTree(childPath);
return result;
}
function merge (a, b) {
for (var p in b) {
if (b.hasOwnProperty(p)) {
if (typeof b[p] === "object" && b[p] !== null) {
a[p] = merge(a[p] || {}, b[p]);
} else {
a[p] = b[p];
}
}
}
return a;
}
@t8g
Copy link

t8g commented Nov 24, 2014

var treeify = function (source) {
    source.sort();
    source.reverse();
    var res = [];
    var tmp = [];
    var deep = 0;

    var countslash = function (str) {
        return (str.match(/\//g) || []).length;
    }

    for (var i=0; i<source.length; i++) {
        if (!deep) deep = countslash(source[i]);

        var cs = countslash(source[i]);
        if (cs === deep) {
            tmp.push({ name: source[i], children: [] });
        } else if (cs < deep) {
            tmp = [{ name: source[i], children: tmp }];
            deep = cs;
        } else {
            res = res.concat(tmp);
            tmp = [{ name: source[i], children: [] }];
            deep = cs;
        }
    }

    return res.concat(tmp);
};

@naholyr
Copy link
Author

naholyr commented Nov 24, 2014

👍

@naholyr
Copy link
Author

naholyr commented Nov 24, 2014

Ah en fait bof, sur mon exemple ça donne ça :

[
  {
    "name": "a/b",
    "children": [
      {
        "name": "e",
        "children": []
      },
      {
        "name": "a/c/d",
        "children": []
      }
    ]
  }
]

chelou non ?

@t8g
Copy link

t8g commented Nov 24, 2014

Ah oui c'est bof

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment