Skip to content

Instantly share code, notes, and snippets.

@newpost
Created July 23, 2020 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newpost/04f3513479922c15d335f0bd49234031 to your computer and use it in GitHub Desktop.
Save newpost/04f3513479922c15d335f0bd49234031 to your computer and use it in GitHub Desktop.
function createNode(path, tree) {
const name = path.shift();
const idx = tree.findIndex((e) => {
return e.name === name;
});
if (idx < 0) {
tree.push({
name: name,
children: [],
leaf: path.length === 0,
});
if (path.length !== 0) {
createNode(path, tree[tree.length - 1].children);
}
} else {
createNode(path, tree[idx].children);
}
}
export default function parse(data) {
const tree = [];
for (let i = 0; i < data.length; i++) {
const path = data[i];
const split = path.split("/");
createNode(split, tree);
}
return tree;
}
@newpost
Copy link
Author

newpost commented Jul 23, 2020

parse(["1/2/3", "2/3", "1/2/4"]);

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