Many times, when processing a tree, the natural tendency is to reach for a recursive function. But recursive functions can be hard to grok and also run into call-stack issues. Try a queue instead.
For example, I wanted to find all clean tasks in my tasks directory. You just have to tell the queue processing function what to do with each item, and how to collect more items into the queue from each item.
var queue = require('./processQueue');
var tasks = require('require-dir')('.', { recurse: true });
var cleanTasks = [];
var process = function (item) {
if (item.clean) {
cleanTasks.push(item.name + '/clean');
}
};
var collect = function (item, queue) {
for (var key in item.tasks) {
if (key === 'clean') { continue; }
queue.push({
name: (item.name ? '/' : '') + key,
tasks: item.tasks[key]
});
}
};
queue([ { name: '', tasks: tasks } ], process, collect);
console.log(cleanTasks);
And that's all there is to process a tree queue style: Pop, Process, Collect!