Skip to content

Instantly share code, notes, and snippets.

@kenbellows
Created April 17, 2017 21:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenbellows/935906d017ab47d6df638701b79fcbd9 to your computer and use it in GitHub Desktop.
Save kenbellows/935906d017ab47d6df638701b79fcbd9 to your computer and use it in GitHub Desktop.
Log a binary tree data structure to the console
/**
* Recursively print a binary tree data structure
* @param {function} printFn function used to print output; called with a single string argument
* @param {object} node current node object
* @param {string|function} leftKey name of current node's left child property, or a function that accepts the
* current node and returns the left child node
* @param {string|function} rightKey name of current node's right child property, or a function that accepts the
* current node and returns the right child node
* @param {string|function} displayKey property to display, or a function that returns a display string
* @param {string} [indent=''] current indentation string; mostly used to build up indentation across levels
* of recursion, but may be used to provide a prefix for all printed lines
*/
function printNode(printFn, node, leftKey, rightKey, displayKey, indent) {
// default to empty string to avoid logging the word 'undefined'
indent = indent || '';
// current item's indentation prefix
var prefix = indent+'\\-';
var leftChild = leftKey.constructor === Function ? leftKey(node) : node[leftKey],
rightChild = rightKey.constructor === Function ? rightKey(node) : node[rightKey];
var displayStr = displayKey.constructor === Function ? displayKey(node) : node[displayKey];
printFn(prefix+' '+displayStr);
// recurse left
if (!!leftChild) printNode(printFn, leftChild, leftKey, rightKey, displayKey, indent+(!!rightChild?' |':' '));
// recurse right
if (!!rightChild) printNode(printFn, rightChild, leftKey, rightKey, displayKey, indent+' ');
}
/** Wrapper around {link:printNode} that always uses console.log() as the print function **/
var logNode = printNode.bind(null, console.log.bind(console));
/* Sample output from a simple Rope tree structure implementation holding the string "The quick brown fox jumps over the lazy dog.":
> logNode(rope.root, node=>rope.nodes[node.left], node=>rope.nodes[node.right], node=>(node.leaf ? '"'+node.value+'"' : node.weight))
\- 32
| \- 16
| |\- 8
| | |\- 4
| | | |\- "The "
| | | \- "quic"
| | \- 4
| | |\- "k br"
| | \- "own "
| \- 8
| |\- 4
| | |\- "fox "
| | \- "jump"
| \- 4
| |\- "s ov"
| \- "er t"
\- 12
\- 8
|\- 4
| |\- "he l"
| \- "azy "
\- 4
\- "dog."
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment