Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Last active June 11, 2018 21:58
Show Gist options
  • Select an option

  • Save pinkmomo027/60ed5fb3b523f5c93d316bb76e80f7dc to your computer and use it in GitHub Desktop.

Select an option

Save pinkmomo027/60ed5fb3b523f5c93d316bb76e80f7dc to your computer and use it in GitHub Desktop.
build html tree with stack
class Node {
constructor(value, parent) {
this.value = value;
this.parent = parent;
this.children = [];
}
add(child) {
this.children.push(child);
}
print(level=0) {
let indent = "";
for (let i = 0; i < level * 2; i++) {
indent += " ";
}
process.stdout.write(`${indent}value : ${this.value} \n`);
if(this.children.length == 0) {
process.stdout.write(`${indent}children: --- none\n`);
} else {
process.stdout.write(`${indent}children: --- below\n`);
this.children.forEach(child => {
child.print(level+1);
});
}
}
}
const tags = [
'<html>', '<head>', '<script>', '</script>', '</head>',
'<body>','<div>', '</div>', '<div>', '</div>', '</body>', '</html>',
];
function isClosingTag(str) {
return str.indexOf('</') >= 0;
}
function parse(tags) {
let stack = [];
let current;
let root;
tags.forEach( tag => {
if(isClosingTag(tag)) {
stack.pop();
current = current.parent;
} else {
stack.push(tag)
let newNode = new Node(tag, current);
if (root == null) {
root = newNode;
}
if (current == null) {
current = newNode;
} else {
current.add(newNode);
current = newNode;
}
}
});
root.print();
}
parse(tags);
// value : <html>
// children: --- below
// value : <head>
// children: --- below
// value : <script>
// children: --- none
// value : <body>
// children: --- below
// value : <div>
// children: --- none
// value : <div>
// children: --- none
// [Finished in 0.1s]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment