Reputation: 567
I'm trying to walk a chain of parent->child relationships until we reach a parent that does not have its own parent. If the child has a parent, then we store that parent object in the array along with any parents of that parent. If the parent doesn't have a parent, we store an empty array.
Here's some pseudo-JSON showing the data-structure I want.
Node3 = { // Node 3
parent: { // Node 2
parent: { // Node 1
parent: null,
parentTree: []
},
parentTree: [Node1]
},
parentTree: [Node2, Node1]
}
Here is the constructor function and the recursive method so far...
function Node(parent) {
this.parent = typeof parent !== 'undefined' ? parent : null;
}
Node.prototype.getParentTree = function() {
if(typeof this.parentTree === "undefined") {
if (this.parent !== null) {
this.parentTree = this.parent.getParentTree();
this.parentTree.push(this.parent);
} else {
this.parentTree = [];
}
}
return this.parentTree;
}
Here is how I'm testing the method:
var node1 = new Node();
var node2 = new Node(node1);
var node3 = new Node(node2);
node3.getParentTree();
The problem with the current method is that the parentTree for node1, node2, and node3 all have length === 2. When you inspect the objects in parentTree they contains pairs of sub-objects to infinity.
Upvotes: 2
Views: 1677
Reputation: 664620
this.parentTree = this.parent.getParentTree(); this.parentTree.push(this.parent);
That way, both the parent's and child's parentTree
refer to the very same Array object - so you're appending the new node to the parent's tree as well.
Create a copy of the array by using slice
:
return this.parentTree.slice(); // every time the getter is called
or
this.parentTree = this.parent.getParentTree().slice(); // only for manipulating
Upvotes: 2