Traversing a uncalculable nested array backwards, node traversal - Javascript? -
i have object has structure so
{ this.parent: undefined, this.nodes: [] }
inside nodes
can number of objects same structure, there parent set of object has nodes array property. object follows pattern top level object have nested nodes potentially quite deep.
i add method top level object search of nodes in reverse. example of trying achieve below except function searching forward.
{ this.parent: undefined, this.nodes: [], this.searchforward: function() { this.nodes.foreach(function(node) { this.searchforward.call(this, node); }, this); } }
the searchforward
function above search nodes deep can go, , move onto next node in line etc etc etc.
i trying write function recursively search deepest child parent (essentially above in reverse).
any ideas me started great, thank you.
first of all, if want traverse path root, that's simple. (i'm pretty sure that's not want, though.)
this.searchup: function() { var parnt = this.parent; while (parnt) { // something, if want parnt = parnt.parnt; } }
the first thing considered call searchforward
in "do something" section. work, strikes me inefficient - each time go parent, you'll search through nodes you've searched. still, on own should work. (as long you're calling searchforward searchup, there's no risk of infinite loop.)
we can make bit more complex , avoid redundancy adding flag. you'd need modify searchforward
, make function similar it:
this.initializesearched: function() { this.nodes.foreach(function(node) { this.searched = false; this.initializesearched.call(this, node); }, this); } this.searchforward: function() { this.nodes.foreach(function(node) { if (this.searched) { continue; } this.searchforward.call(this, node); }, this); }
once have this, should able put searchforward
in "do something" section of searchup
, done.
Comments
Post a Comment