JSFiddle - React, Tailwind, and code Playground
by Juha Lindstedt
Babel + JSX
const table = document.createElement('table')
document.body.appendChild(table)
updateTable(table, [
[ 1, 2 ],
[ 3, 4, 5 ],
[ 6, 7, 8, 9 ]
])
setTimeout(() => {
updateTable(table, [
[ 1, 2, 3, 4 ],
[ 5, 6, 7 ],
[ 8, 9 ]
])
}, 1000)
function updateTable (table, data) {
const rowLookup = table._lookup || (table._lookup = [])
setChildren(table, updateRows(rowLookup, data))
}
function updateRows (rowLookup, rows) {
return rows.map((row, y) => {
const tr = rowLookup[y] || (rowLookup[y] = document.createElement('tr'))
const cellLookup = tr._lookup || (tr._lookup = [])
setChildren(tr, updateCells(cellLookup, row))
return tr
})
}
function updateCells (cellLookup, cells) {
return cells.map((cell, x) => {
const td = cellLookup[x] || (cellLookup[x] = document.createElement('td'))
td.textContent = cell
return td
})
}
function setChildren (parent, children) {
let traverse = parent.firstChild
for (let i = 0; i < children.length; i++) {
const child = children[i]
if (child == null) {
return
}
if (child === traverse) {
traverse = traverse.nextSibling
} else if (traverse) {
parent.insertBefore(child, traverse)
} else {
parent.appendChild(child)
}
}
while (traverse) {
const next = traverse.nextSibling
parent.removeChild(traverse)
traverse = next
}
}