Created
October 17, 2014 11:38
-
-
Save danielstocks/5da83982d3b4c7b503a0 to your computer and use it in GitHub Desktop.
Pretty print a JavaScript Tree Data Structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Thank you! Just what I need.
is there an approach that doesnt include defining the indent outside of the function?
@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
Nice, thanks