I have a tree of objects composed with the following structure:
interface Node {
name: string;
children?: Node[];
}
Where, for example, { name: "foo", children: [ { name: "bar" } ] } is a valid tree. I'm trying to get the address of an arbitrary node, that can be a leaf, returned as an array of the path to arrive it, where the node will be compared by object reference. Example given, I have the following structure:
var data = {
name: "Languages",
children: [{
name: "Functional",
children: [
{ name: "OCaml" },
{ name: "Haskell" },
{ name: "Erlang" }
]
}, {
name: "Imperative",
children: [
{ name: "BASIC" },
{ name: "Clipper" }
]
}]
};
It is expected that, for example, if I have a reference for OCaml stored in a variable called ocaml that points exactly to that reference in memory, an array of steps be returned with the path to reach it, that would be, in this case, [0, 0].
I already can locate the object, but I'm not able to store the previous index, because this is non-deterministic:
var tree = function(struct, cmp) {
if (struct.children) {
var lookup = [];
for (var i = 0; i < struct.children.length; i++) {
lookup.push(tree(struct.children[i], cmp));
}
return lookup;
} else {
if (struct === cmp) {
return "PASS";
}
return "FAIL";
}
}
I can find the element, but how can I store the previous indexes to reach it from the base?
interface Node { parent: Node; name: string; ...}