Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Last active August 29, 2015 14:12
Show Gist options
  • Save jehoshua02/51c637c21629325d0346 to your computer and use it in GitHub Desktop.
Save jehoshua02/51c637c21629325d0346 to your computer and use it in GitHub Desktop.
Example of how to process a tree with a queue (rather than a recursive function). It's just pop, process, collect inside a do-while.

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!

var processQueue = function (queue, process, collect) {
do {
var item = queue.pop(); // POP!
process(item); // PROCESS!
collect(item, queue); // COLLECT!
} while (queue.length > 0);
};
module.exports = processQueue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment