Skip to content

Instantly share code, notes, and snippets.

@igroff
Last active July 15, 2019 09:59
Show Gist options
  • Save igroff/b572ed05a682ec6ea14b to your computer and use it in GitHub Desktop.
Save igroff/b572ed05a682ec6ea14b to your computer and use it in GitHub Desktop.
/* Takes a list ofdelimited strings, where the delimiter is intended to imply
* a hierarchy ( somewhat like a file system path ) and turns it into
* a tree-like structure consisting of nodes looking something like
* { name: "", children: [] }
* The tree starts at the root node, which is ( no foolin' ) called
* root. So the top (root) node is:
* { name: "root", children: [xxx] }
*/
function listOfDelimitedStringsToTree(lines, delimiter){
function stringTreeToObjectTree(root){
var childNodes = []
for(var name in root){
childNodes.push({name: name, children: stringTreeToObjectTree(root[name])});
}
return childNodes;
}
var tree = {};
// for each of our delimited strings
for (var i=0;i<lines.length;i++){
// split things up by delimiter, which gives us
// one path through the tree
var tokens = lines[i].split(delimiter);
// make a reference to the working branch so we can
// keep our root around (ref'd by tree)
var workingTree = tree;
// walk through the tokens building this branch
// of our tree
for(var ii=0;ii<tokens.length;ii++){
var token = tokens[ii];
workingTree[token] = workingTree[token] || {};
workingTree = workingTree[token];
}
}
return { name:"root", children: stringTreeToObjectTree(tree) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment