Last active
September 20, 2020 11:54
-
-
Save tusharmath/01c04ee761f9196c0a79845c0e170706 to your computer and use it in GitHub Desktop.
Virtual DOM library in 500bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const typeOf = ob => ob.toString() | |
const forEach = (fn, l) => typeOf(l) === '[object Object]' | |
? forEach(k => fn(l[k], k), Object.keys(l)) | |
: Array.from(l).forEach(fn) | |
export const patch = (elm, node) => { | |
if(elm === node) return elm | |
if(typeOf(elm) === '[object Text]') { | |
elm.textContent = node.textContent | |
return elm | |
} | |
const [len0, len1] = [elm.childNodes.length, node.childNodes.length] | |
if(len0 !== len1) { | |
elm.parentNode.replaceChild(node, elm) | |
return node | |
} | |
else forEach((node, i) => patch(elm.childNodes[i], node), node.childNodes) | |
if(elm.classList.length !== node.classList.length) elm.classList = node.classList | |
return elm | |
} | |
export const h = (...t) => { | |
const [sel, options, children] = t | |
if(t.length === 1) return h(t[0], {}, []) | |
if(t.length === 2) return h(t[0], {}, t[1]) | |
const [type, ...classNames] = sel.split('.') | |
const elm = document.createElement(type) | |
forEach(i => elm.classList.add(i), classNames) | |
forEach(i => i instanceof HTMLElement ? elm.appendChild(i) : elm.innerText+= i, children) | |
forEach((listener, event) => elm[event] = listener, options) | |
return elm | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Usage — https://jsbin.com/yizutumiqa/edit?js,output