Traversing a tree

A common pattern is traversing a tree, and you find yourself writing the same recursive code over an over. Although it’s a very simple problem, people often have trouble with it. Here’s a general pattern you can use.

Let’s say you have some data that looks like this – a classic tree structure.

Typically you want to traverse this and do something at each node – using a pattern like this we can generalize …
So in the case of our data we want to just log the name and depth of each tree node
which gives this result
Here’s the traverseTree function, which you can copy from here or use directly from the cUseful library.
For more on snippets topic, see: