How to generate a TOC (Table of Contents) in Node.js based on a list

“I am using Node.js to generate a TOC in HTML. How can I generate this output with high performance?”

Source:

const data = [
{ text: "A2", level: 2 },
{ text: "B2", level: 2 },
{ text: "B3", level: 3 },
{ text: "B3", level: 3 },
{ text: "C2", level: 2 },
{ text: "C3", level: 3 },
{ text: "C4", level: 4 },
{ text: "C4", level: 4 },
];

Experted:

<ul class="markdownIt-TOC">
    <li><a href="#A2">A2</a></li>
    <li><a href="#B2">B2</a></li>
    <li><a href="#C2">C2</a></li>
    <ul>
        <li><a href="#C3">C3</a></li>
    </ul>
    <ul>
        <li><a href="#C4">C4</a></li>
        <li><a href="#C4">C4</a></li>
    </ul>
</ul>