Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created April 30, 2024 03:13
Show Gist options
  • Save amitasaurus/acc74e54ce1cd20c5094a008fbceab93 to your computer and use it in GitHub Desktop.
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.
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');
}
@amitasaurus
Copy link
Author

const tree = {
  tag: 'body',
  children: [
    { tag: 'div', children: [{ tag: 'span', children: ['foo', 'bar'] }] },
    { tag: 'div', children: ['baz'] },
  ],
};

serializeHTML(tree);
// Output:
`<body>
  <div>
    <span>
      foo
      bar
    </span>
  </div>
  <div>
    baz
  </div>
</body>`;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment