Lumberjack
A library for working with trees.
API
Tree
Suppose you have a tree:
var someTree = {
name: 'Jake',
id: 1,
children: {
b: {
name: 'Todd',
id: 2,
children: {
c: {
name: 'Mary',
id: 3
}
}
},
d: {
name: 'Tricia',
id: 4
}
}
};
And suppose you need to find something in that tree:
var Tree = require('lumberjack-tree').Tree;
var tree = new Tree(someTree, );
You can search breadth-first:
tree.breadthFirst(tree.tree, { name: 'Mary' }, function(err, node) {
console.log(node);
});
or depth-first:
tree.depthFirst(tree.tree, { id: 4 }, function(err, node) {
console.log(node);
});
You can flatten the tree:
tree.flatten(tree.tree);
console.log(tree.flattened);
And you can rebuild it:
tree.rebuild(tree.flattened['1'], { id: 1 });
console.log(tree.tree);
Options
-
children (String; default: 'children'): The name of subnodes in your tree
- The value of this property should be an
Array; however, if you flatten and then rebuild your tree, it will be made into an Array for you.
-
flat (Boolean; default: false): If you pass a flat tree to the Tree constructor, mark this flag as true so the constructor can build the nested tree for you. (It takes as root the 0th item in the Object or Array that it receives.)
-
identifier (String; default: 'id'): The key that uniquely identifies each node in your tree
-
rememberPath (Boolean; default: false): Instructs the Lumberjack instance to return its traversal path for your search. If true, provider your callback with a third parameter:
var tree = new Tree(someTree, { rememberPath: true });
tree.breadthFirst(tree.tree, { id: 3 }, function(err, node, path) {
console.log(path);
});
tree.depthFirst(tree.tree, { id: 3 }, function(err, node, path) {
console.log(path);
})
Lumberjack
Lumberjack can compare two trees:
var Tree = require('lumberjack-tree').Tree;
var Lumberjack = require('lumberjack-tree').Lumberjack;
var someTree = {
name: 'Jake',
id: 1,
children: [
{
name: 'Todd',
id: 2,
children: [
{
name: 'Mary',
id: 3
}
]
},
{
name: 'Tricia',
id: 4
}
]
};
var anotherTree = {
name: 'Jake',
id: 1,
children: [
{
name: 'Todd',
id: 2,
children: [
{
name: 'Mary',
id: 3
},
{
name: 'Bill',
id: 5
}
]
}
]
};
var tree1 = new Tree(someTree);
var tree2 = new Tree(anotherTree);
var lumberjack = new Lumberjack();
lumberjack.compare(tree1, tree2, { id: 1 }, function(err, markedTree) {
console.log(markedTree);
});
TODO
- Make
Tree.rebuild properly asynchronous
Tests
cd [lumberjack_root_directory]
make test