Dealing with recursion

You'll have noticed by now there is recursion involved in almost every function. Here's a good time to look at the fundamentals of recursion in these kind of tree objects. Each object has children, each of which may have their own children. The simplest way to navigate these kind of structure is with recursion.

Here's a simple example of adding an analytics object in which to store the accumulated page views for each page

 * this is a stats package to accumulate pageview summaries in
 * @param {PageTreeObject} root the top of the branch to look at
 * @param {object} options
function addAnalyticStats (root, options) {
  options.periods.forEach (function (d) {;
  root.children.forEach (function (d) {
    addAnalyticStats ( d , options);

Each recursive function follows the same pattern.
  • do something with the current object
  • call itself repeatedly with each of its children
A good thing about using recursion is that it forces you to use consistent patterns - it usually completely works, or totally screws up.

For help and more information join our forum,follow the blog or follow me on twitter .