Created
November 24, 2014 11:06
-
-
Save naholyr/b6e38108d13a1ed41b19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Ah en fait bof, sur mon exemple ça donne ça :
[
{
"name": "a/b",
"children": [
{
"name": "e",
"children": []
},
{
"name": "a/c/d",
"children": []
}
]
}
]
chelou non ?
Ah oui c'est bof
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍