Last active
February 24, 2019 09:45
-
-
Save asci/07ba38588cce51636928b58ac8290bd6 to your computer and use it in GitHub Desktop.
tree functions
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
function walkTree(onEachChildren, childrenKey = "children") { | |
return function treeWalker(elem, level = 0) { | |
onEachChildren(elem, level); | |
if (elem[childrenKey]) { | |
elem[childrenKey].forEach(item => treeWalker(item, level + 1)); | |
} | |
}; | |
} | |
// how to use | |
const renderTree = walkTree((elem, level) => { | |
console.log(elem.name.padStart(level + elem.name.length, " ")); | |
}); | |
renderTree(tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment