Created
March 1, 2019 02:37
-
-
Save Damimd10/7ab52ab1503b9f1ef3ed079bfdc30ea6 to your computer and use it in GitHub Desktop.
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 createNode(key) { | |
const children = [] | |
return { | |
key, | |
children, | |
addChild(childKey) { | |
const childNode = createNode(childKey) | |
children.push(childNode) | |
return childNode | |
} | |
} | |
} | |
function createTree(rootKey) { | |
const root = createNode(rootKey) | |
return { | |
root, | |
print() { | |
let result = '' | |
function traverse(node, visitFn, depth) { | |
visitFn(node, depth) | |
if (node.children.length) { | |
node.children.map(n => traverse(n, visitFn, depth + 1)) | |
} | |
} | |
function addKeyToResult(node, depth) { | |
result += | |
result.length === 0 | |
? node.key | |
: `\n${' '.repeat(depth * 2)}${node.key}` | |
} | |
traverse(root, addKeyToResult, 0) | |
return result | |
} | |
} | |
} | |
const dom = createTree('html') | |
const head = dom.root.addChild('head') | |
const body = dom.root.addChild('body') | |
const title = head.addChild('title - egghead Tree Lesson') | |
const header = body.addChild('header') | |
const main = body.addChild('main') | |
const footer = body.addChild('footer') | |
const h1 = header.addChild('h1 - Tree Lesson') | |
const p = main.addChild('p - Learn about trees!') | |
const copyright = footer.addChild(`Copyright ${new Date().getFullYear()}`) | |
console.log(dom.print()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment