Skip to content

Instantly share code, notes, and snippets.

@danielstocks
Created October 17, 2014 11:38
Show Gist options
  • Save danielstocks/5da83982d3b4c7b503a0 to your computer and use it in GitHub Desktop.
Save danielstocks/5da83982d3b4c7b503a0 to your computer and use it in GitHub Desktop.
Pretty print a JavaScript Tree Data Structure
// Example implementation: http://jsfiddle.net/2f7w2fpn/
var indent = 1;
function walk(tree) {
tree.forEach(function(node) {
console.log('--' + Array(indent).join('--'), node.key);
if(node.children) {
indent ++;
walk(node.children);
}
if(tree.indexOf(node) === tree.length - 1) {
indent--;
}
})
}
// Usage
walk([
{
key: 'fruits',
children: [
{
key: 'apple'
},
{
key: 'pear'
},
{
key: 'orange'
}
]
},
{
key: 'vegetables',
children: [
{
key: 'carrot',
children: [
{
key: 'orange'
},
{
key: 'red'
},
{
key: 'yellow'
}
]
},
{
key: 'cucumber'
},
{
key: 'tomato'
}
]
}
]);
// Output
// -- fruits
// ---- apple
// ---- pear
// ---- orange
// -- vegetables
// ---- carrot
// ------ orange
// ------ red
// ------ yellow
// ---- cucumber
// ---- tomato
@thEpisode
Copy link

Nice, thanks

@jumpinjan
Copy link

Thank you! Just what I need.

@minmaxdata
Copy link

is there an approach that doesnt include defining the indent outside of the function?

@danielstocks
Copy link
Author

@minmaxdata not sure what you are trying to achieve here, but if you're talking about avoiding creating a global indent variable you could wrap it in another function to create a scope, like so:

function walk(tree) {
  var indent = 1;
  function innerWalk(tree) {
    tree.forEach(function(node) {
      console.log('--' + Array(indent).join('--'), node.key);
      if(node.children) {
        indent ++;
        innerWalk(node.children);
      }
      if(tree.indexOf(node) === tree.length - 1) {
        indent--;
      }
    })
  }
  innerWalk(tree);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment