Skip to content

Instantly share code, notes, and snippets.

@tusharmath
Last active September 20, 2020 11:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tusharmath/01c04ee761f9196c0a79845c0e170706 to your computer and use it in GitHub Desktop.
Save tusharmath/01c04ee761f9196c0a79845c0e170706 to your computer and use it in GitHub Desktop.
Virtual DOM library in 500bytes
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
}
@tusharmath
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment