Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Created December 26, 2013 18:50
Show Gist options
  • Save nemtsov/8137320 to your computer and use it in GitHub Desktop.
Save nemtsov/8137320 to your computer and use it in GitHub Desktop.
A few types of recursive asynchronous algorithms.
var page = require('./page');
function getFullPage(id, cb) {
var combined = {id: id, modules: []};
_get(id, combined, cb);
}
function _get(id, combined, cb) {
function onGet(err, page) {
if (err) return cb(err);
_combine(combined, page);
page.parentId ?
_get(page.parentId, combined, cb) :
cb(null, combined);
}
page.get(id, onGet);
}
function _combine(combined, page) {
combined.modules = combined.modules.concat(page.modules);
}
getFullPage('child', function (err, page) {
if (err) throw err;
console.log(page);
console.log('ok');
});
var page = require('./page');
/**
* +:
* - good for one-to-many relationships,
* where there can be many parentIds
* within a page; or if many modules
* needed to be retrieved asynchronously
* within each page
* -:
* - stack push / pop overhead
* - more verbose (by 2 lines)
*/
function getFullPage(id, cb) {
var combined = {id: id, modules: []};
_get([id], combined, cb);
}
function _get(stack, combined, cb) {
var id = stack.pop();
if (!id) return cb(null, combined);
function onGet(err, page) {
if (err) return cb(err);
_combine(combined, page);
stack.push(page.parentId);
_get(stack, combined, cb);
}
page.get(id, onGet);
}
function _combine(combined, page) {
combined.modules = combined.modules.concat(page.modules);
}
getFullPage('child', function (err, page) {
if (err) throw err;
console.log(page);
console.log('ok');
});
exports.get = function get(id, cb) {
process.nextTick(function () {
var page;
switch (id) {
case 'child':
page = {id: 'child', parentId: 'parent', modules: ['c1', 'c2']};
break;
case 'parent':
page = {id: 'parent', parentId: 'grand_parent', modules: ['p1']};
break;
case 'grand_parent':
page = {id: 'grand_parent', modules: ['gp1']};
break;
}
cb(null, page);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment