Recursive function in javascript

This is an example to update a tree list object with nodes (the bonus is to set a flag for each element if there is something different between parent node and children nodes):

// Recursive function in order to update all nodes.
_updateSecuredBranchNodesState:function(ctx, pNode){
    return (function (ctx, pNode) {
        pNode.hasDifferentChildrenBranchCountries = false;
        _.each(pNode.nodes, function(cNode, index){
	    //only reset the flag at the beginning of the iteration
            if(index==0){cNode.hasDifferentChildrenBranchCountries = false;}
            ctx._updateSecuredBranchNodesState(ctx, cNode);
	    //don't treat the root branch
                    pNode.hasDifferentChildrenBranchCountries = true;
                    cNode.hasDifferentChildrenBranchCountries = true;
                } else {
                    for(var i=0; i<pNode.branch.countries.length;i++){
                        var pCountry = pNode.branch.countries[i];
                        var found = false;
                        _.each(cNode.branch.countries, function(cCountry){
                                found = true;
                        if(!found) {
                            pNode.hasDifferentChildrenBranchCountries = true;
                            cNode.hasDifferentChildrenBranchCountries = true;
		    // update the parent flag
                    pNode.hasDifferentChildrenBranchCountries = true;
    })(ctx, pNode);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s