Created
April 30, 2024 03:13
-
-
Save amitasaurus/acc74e54ce1cd20c5094a008fbceab93 to your computer and use it in GitHub Desktop.
Given an object which resembles a DOM tree, implement a function that serializes the object into a formatted string with proper indentation (one tab (\t character) per nesting level) and one tag per line.
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
type Element = { tag: string; children: Array<string | Element> }; | |
export default function serializeHTML(element: Element): string { | |
let html: string[] = []; | |
html.push(`<${element.tag}>`); | |
function traverseHTML(children: (string | Element)[]) { | |
children.forEach((child: string | Element) => { | |
let tag = '\n\t'; | |
if (typeof child === 'string') { | |
html.push(child); | |
} else { | |
html.push(serializeHTML(child)); | |
} | |
html.push(tag); | |
}); | |
} | |
traverseHTML(element.children); | |
html.push(`</${element.tag}>`); | |
return html.join('\n'); | |
} |
Author
amitasaurus
commented
Apr 30, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment