javascript - Calling same function in multiple object's context? -
i have object structure so;
{ this.parent = undefined; this.children = []; }
all values in children
have same structure above except parent
would reference object has child.
how can iterate on children of children etc in child's object context?
i know how can loop children 1 object
obj.children.foreach(function(child) { });
but how can iterate children of children, when children 10-20-30 deep heirachy?
use recursion.
function deepforeach(node, fn) { fn(node); node.children.foreach(function(child) { deepforeach(child, fn); }); } deepforeach(obj, function(obj) { console.log(obj); });
the way works becomes evident if state in plain english:
- if there no children, call callback node. (base case)
- if there children, first deal ourself, , whole procedure each child.
this type of recursion called preorder traversal.
Comments
Post a Comment