This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
118. Virtual DOM II - createElement
/**
* @typedef {Object} MyElement
* @property {string} tagName
* @property {Object.<string,string>} [props]
* @property {(MyElement|string)[]} [children]
*/
/**
* @param {string} tagName
* @param {Object.<string,string>} [props]
* @param {(MyElement|string)[]} [children]
* @return {MyElement}
*/
function createElement(tagName, props = {}, ...children) {
return {
tagName,
props,
children,
}
}
/**
* @param {MyElement} element
* @return {HTMLElement|Text}
*/
function renderElement(element) {
if (typeof element === 'string') {
return document.createTextNode(element)
}
const { tagName, props, children } = element
const htmlElement = document.createElement(tagName)
// Assign all props to the HTMLElement
for (const [propKey, propValue] of Object.entries(props)) {
htmlElement.setAttribute(propKey, propValue)
}
// Append all the children
if (children) {
for (const child of children) {
htmlElement.appendChild(renderElement(child))
}
}
return htmlElement
}
/**
* @param {MyElement} element
* @param {HTMLElement} container
*/
function render(element, container) {
const output = renderElement(element)
container.appendChild(output)
}