I have this Data Structure:
var tree = {
name: "docs",
type: "dir",
full: "/home/docs",
children: [
{
name: "folder2",
type: "dir",
full: "/home/docs/folder2",
children: [
{
name: "file2.txt",
type: "file",
full: "/home/docs/folder2/file2.txt"
}
]
},
{
name: "file1.txt",
type: "file",
full: "/home/docs/file1.txt"
}
]
}
This data structure represents a contents of the folder of the User, so it may vary on every user's machine.
1 thing common in this is every element represents either a file or a directory, if it's a directory it will have the property type: "dir" else it will have type: "file".
if the element is a directory it will also have a children property which will be a array of such elements.
every element also has name property like folder/file name & it has a full property which is a unique string, which defines where the folder/file is on the user's filesystem.
I have written this algorithm:
var tree = {
name: "docs",
type: "dir",
full: "/home/docs",
children: [
{
name: "folder2",
type: "dir",
full: "/home/docs/folder2",
children: [
{
name: "file2.txt",
type: "file",
full: "/home/docs/folder2/file2.txt"
}
]
},
{
name: "file1.txt",
type: "file",
full: "/home/docs/file1.txt"
}
]
}
function FindChildrenInTree(fullPath, treeObj) {
if (treeObj.type != "dir") { return null; }
if (treeObj.children == null) { return null }
if (treeObj.full == fullPath) { return treeObj; }
for (var i = 0; i < treeObj.children.length; i++) {
if (treeObj.children[i].full == fullPath) {
return treeObj.children[i];
} else {
var result = FindChildrenInTree(fullPath, treeObj.children[i]);
if (result != null) return result;
}
}
return null;
}
console.log(FindChildrenInTree("/home/docs/folder2", tree))
This algorithm finds a folder in the given tree object & returns it, but instead of return the item i have found i want to add a children property that item in the given tree.
So for example i have the above given tree, i give the algorithm the item's unique path, the tree & the children array i want to add, how will i do it, i can't find any way.
if (treeObj.full == fullPath) { return treeObj; }is your "success" path, meaning you found the item you were looking for. So if you want to add logic into that condition, you would do it there. i.e.{ treeObj.children = []; return treeObj; }or whatever you want to dochildrenproperty? But if it was a directory, then it already haschildren. If it was a file, it should not get achildrenproperty. Or did you mean that you want to add an entry inside an existingchildrenproperty? Can you give an example of how you would call the function, and what the expected result would be?