I needed to generate the HTML strings from a tree object with proper indentation. e.g.
{
children: [
{ tag: 'div', children: [{ tag: 'span', children: ['bar1', 'bar2'] }] },
{ tag: 'div', children: ['baz'] },
],
tag: 'body',
}
would become
<body>
<div>
<span>
bar1
bar2
</span>
</div>
<div>
baz
</div>
</body>
Here is my attempt
function generateHTMLFrom(tree) {
const recur = (node, depth = 0, indent = ' ') => {
if (!node.children) return node
return [
`${indent.repeat(depth * 2)}`,
`<${node.tag}>`,
...node.children.flatMap((child) => recur(child, depth + 1)),
`${indent.repeat(depth * 2)}</${node.tag}>`,
]
}
return recur(tree).join('\n')
}
But the format is actually messed up because the indentation is all wrong
Can someone help me fix this?