Friday, September 25, 2015

Counting all nodes and items in a tree structure (JS)

It's been a long time since last post, and altho this is rather mundane, here is an update:

Case: Im recieving data from the server as a gigantic object tree structure (like shown below). The data is displayed on a webpage in a suitable AngularJS directive. However, when the number of objects are more than 100 the view has to be set to only show a summary. So, how do you count a tree?
Solution:

var CountAllNodesInTree = function (treeObject) {
    this.counter = 0;
    self.countTree = function (treeObj) {
        self.counter = 0;
        self.countLeaves(treeObj);
        return self.counter;
    }

    self.countLeaves = function (treeObj) {
        if (treeObj) {
            self.counter++; // count department
            if (treeObj.Items) {
                self.counter += treeObj.Items.length; 
            }
            if (treeObj.Children) {
                if (treeObj.Children[0]) {
                    for (var i = 0; i < treeObj.Children.length; i++) {
                        if (treeObj.Children[i]) 
                            self.countLeaves(treeObj.Children[i]);
                    }
                }
            }
        }
    }
    return self.countTree(treeObject);
}