Skip to content

Instantly share code, notes, and snippets.

@jimkang
Created August 6, 2013 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimkang/6161874 to your computer and use it in GitHub Desktop.
Save jimkang/6161874 to your computer and use it in GitHub Desktop.
Given a database that you want to retrieve from with async calls, and records in it that represent nodes of a tree (each of which has a 'children' array with containing ids of other node records), here's a way to walk that tree with callbacks. Saving this in case I later decide I need this, after all.
var levelup = require('level');
var _ = require('underscore');
var TreeGetter = function TreeGetter(db, rootNodeId, childDepth, done) {
this.treeGetState = {
db: db,
nodesToGet: 0,
nodesGot: 0,
errors: [],
depthLimit: childDepth,
tree: {},
done: done
};
};
TreeGetter.prototype.getNodeFromDb = function getNodeTreeFromDb(
rootNodeId, depth, parent) {
++this.treeGetState.nodesToGet;
this.treeGetState.db.get(rootNodeId, function getComplete(error, value) {
this.receiveNode(error, depth, parent, value);
}
.bind(this));
};
TreeGetter.prototype.receiveNode = function receiveNode(
error, depth, parent, node) {
if (error) {
this.treeGetState.errors.push(error);
return;
}
++this.treeGetState.nodesGot;
if (parent) {
debugger;
// Replace the id in children with the node object.
var childIndex = parent.children.indexOf(node.id);
parent.children[childIndex] = node;
}
else {
this.treeGetState.tree = node;
}
debugger;
if (depth < this.treeGetState.depthLimit &&
typeof node.children === 'object') {
node.children.forEach(function getNodeChild(childId) {
this.getNodeFromDb(childId, depth + 1, node);
}
.bind(this));
}
this.wrapUpIfComplete();
}
TreeGetter.prototype.wrapUpIfComplete = function wrapUpIfComplete() {
debugger;
if (this.treeGetState.nodesGot >= this.treeGetState.nodesToGet) {
this.treeGetState.done(this.treeGetState.errors, this.treeGetState.tree);
}
};
module.exports.getTree = function getTree(db, nodeId, childDepth, done) {
var treeGetter = new TreeGetter(db, nodeId, childDepth, done);
treeGetter.getNodeFromDb(nodeId, 0, null);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment