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
            if(pNode.id!= ctx.securedBranchesNodes.id){
                if(cNode.branch.countries.length!=pNode.branch.countries.length){
                    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){
                            if(pCountry.country.id== cCountry.country.id){
                                found = true;
                            }
                        });
                        if(!found) {
                            pNode.hasDifferentChildrenBranchCountries = true;
                            cNode.hasDifferentChildrenBranchCountries = true;
                            break;
                        }
                    }
                }
                if(cNode.hasDifferentChildrenBranchCountries){
		    // update the parent flag
                    pNode.hasDifferentChildrenBranchCountries = true;
                }
            }
        });
    })(ctx, pNode);
},

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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