This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
150. Virtual DOM V - JSX 2
Here's the modified code to support nesting elements and functional components:
function h(type, props, ...children) {
return {
type,
props: props || {},
children: flatten(children),
};
}
function flatten(arr) {
return [].concat(...arr);
}
function createElement(node) {
if (typeof node === 'string') {
return document.createTextNode(node);
}
const el = document.createElement(node.type);
setProps(el, node.props);
node.children
.map(createElement)
.forEach(el.appendChild.bind(el));
return el;
}
function setProps(el, props) {
Object.keys(props)
.filter(isProperty)
.forEach(name => setProp(el, name, props[name]));
Object.keys(props)
.filter(isAttribute)
.forEach(name => setAttribute(el, name, props[name]));
}
function isAttribute(name) {
return !isProperty(name) && name !== 'children';
}
function isProperty(name) {
return name === 'value' || name === 'checked';
}
function setAttribute(el, name, value) {
if (value === true) {
el.setAttribute(name, '');
} else if (value !== false && value != null) {
el.setAttribute(name, value);
}
}
function setProp(el, name, value) {
if (isBoolean(value)) {
setBooleanProp(el, name, value);
} else {
el[name] = value;
}
}
function setBooleanProp(el, name, value) {
if (value) {
el[name] = true;
el.setAttribute(name, '');
} else {
el[name] = false;
el.removeAttribute(name);
}
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isFunctionalComponent(component) {
return typeof component === 'function';
}
function render(node, container) {
container.appendChild(createElement(node));
}
const React = {
createElement,
};
const BFE = {
h,
render,
};
// Usage:
const Heading = ({ children, ...rest }) =>
BFE.h('h1', rest, ...children);
const App = () => (
<div className="app">
<Heading>BFE.<i>dev</i></Heading>
<p>
<i>BFE.dev</i> is <b>cool</b>!
</p>
</div>
);
BFE.render(<App />, document.getElementById('root'));
I hope this solution helps! Let me know if you have any questions.