This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
140. Virtual DOM III - Functional Component
Implement the createElement()
and render()
functions to support custom Functional Component.
/**
*
* @typedef MyElement {string|function}
*/
/**
*
* @param {string} tag
* @param {Object|null} attrs
* @param {...MyElement} children
* @return {MyElement}
*/
function createElement(tag, attrs, ...children) {
if (typeof tag === 'function') {
return tag({children, ...attrs});
}
return { tag, attrs, children };
}
/**
*
* @param {MyElement} element
* @param {HTMLElement} container
* @param {HTMLElement|null} [prevDom=null]
* @return {HTMLElement}
*/
function render(element, container, prevDom = null) {
if (typeof element === 'string') {
const textNode = document.createTextNode(element);
return container.appendChild(textNode);
}
if (typeof element === 'function') {
return render(element(), container);
}
const { tag, attrs, children } = element;
let dom;
if (prevDom) {
dom = prevDom;
} else {
dom = document.createElement(tag);
}
for (const name in attrs) {
const value = attrs[name];
if (name === 'className') {
name = 'class';
}
if (name === 'style') {
for (const styleName in value) {
dom.style[styleName] = value[styleName];
}
} else if (name.startsWith('on')) {
const eventName = name.toLowerCase().substr(2);
dom.addEventListener(eventName, value);
} else {
dom[name] = value;
}
}
if (children) {
for (const child of children) {
render(child, dom);
}
}
if (!prevDom) {
container.appendChild(dom);
}
return dom;
}