Skip to content

Instantly share code, notes, and snippets.

@vicsstar
Created December 4, 2018 23:51
Show Gist options
  • Save vicsstar/9a4ad11600f03c59efd6088813ef66a4 to your computer and use it in GitHub Desktop.
Save vicsstar/9a4ad11600f03c59efd6088813ef66a4 to your computer and use it in GitHub Desktop.
Implementation of a simple Tree data structure - tested with the common DOM structure
function createNode(key) {
const children = [];
const attributes = {};
return {
key,
children,
attributes,
addChild(key) {
const child = createNode(key);
children.push(child);
return child;
},
addAttribute(name, value) {
attributes[name] = value;
}
}
}
function createTree(rootKey) {
const root = createNode(rootKey);
return {
root,
addChild(key) {
return root.addChild(key);
},
print() {
let result = '';
const traverse = (node, visitFn, depth) => {
visitFn(node, depth);
if (node.children.length) {
node.children.forEach(child => {
traverse(child, visitFn, depth + 1);
});
}
};
const printKeys = (node, depth) => {
let attributeString =
result.length === 0 ? '' : Object.keys(node.attributes).reduce((acc, attrName) => {
return [...acc, `${attrName}=${node.attributes[attrName]}`];
}, []).join(', ');
attributeString = !attributeString.length ? '' : `[${attributeString}]`;
result += result.length === 0 ? node.key : `\n${' '.repeat(depth * 2)}${node.key} ${attributeString}`;
};
traverse(root, printKeys, 1);
return result;
}
}
}
const dom = createTree('html');
const head = dom.addChild('head');
const body = dom.addChild('body');
const title = head.addChild('title - Learning Algorithms');
const meta = head.addChild('meta - meta tag');
meta.addAttribute('content-type', 'text/html');
meta.addAttribute('author', 'Victor Igbokwe');
body.addAttribute('bgcolor', 'red');
const main = body.addChild('main');
const h1 = main.addChild('h1 - Learning Algorithms', 'p - Algorithms are methods and patterns in solving problems');
h1.addAttribute('style', 'background-color: red')
const p = main.addChild('p - Algorithms are methods and patterns in solving problems');
const hr = main.addChild('hr');
hr.addAttribute('size', '1');
console.log(dom.print());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment