Skip to content

Instantly share code, notes, and snippets.

@ezhillragesh
Last active December 10, 2023 04:23
Show Gist options
  • Save ezhillragesh/0ae50d99a5c1279ab1c9227f64b0476a to your computer and use it in GitHub Desktop.
Save ezhillragesh/0ae50d99a5c1279ab1c9227f64b0476a to your computer and use it in GitHub Desktop.
Dynamic DOM rendering with a reconciler mechanism using a virtual DOM approach.
let virtualDocument = [];
function updateDOMElements(existingDOM, currentDOM) {
var parentElement = document.getElementById("mainArea");
let additions = 0, removals = 0, modifications = 0;
currentDOM.forEach(function(item) {
var existingItem = existingDOM.find(function(oldItem) {
return oldItem.id === item.id;
});
if (existingItem) {
modifications++;
var existingChild = document.querySelector(`[data-id='${item.id}']`);
existingChild.children[0].innerHTML = item.title;
existingChild.children[1].innerHTML = "Author: " + item.author;
} else {
additions++;
var childElement = document.createElement("div");
childElement.dataset.id = item.id;
var titleElement = document.createElement("span");
titleElement.innerHTML = item.title;
var authorElement = document.createElement("span");
authorElement.innerHTML = "Author: " + item.author;
var deleteButtonElement = document.createElement("button");
deleteButtonElement.innerHTML = "Delete";
deleteButtonElement.setAttribute("onclick", "removeBook(" + item.id + ")");
childElement.appendChild(titleElement);
childElement.appendChild(authorElement);
childElement.appendChild(deleteButtonElement);
parentElement.appendChild(childElement);
}
});
existingDOM.forEach(function(oldItem) {
if (!currentDOM.some(item => item.id === oldItem.id)) {
removals++;
var childToRemove = document.querySelector(`[data-id='${oldItem.id}']`);
parentElement.removeChild(childToRemove);
}
});
console.log(additions);
console.log(modifications);
console.log(removals);
}
function updateVirtualDocument(data) {
let existingDOM = [...virtualDocument];
virtualDocument = data.map(item => {
return {
id: item.id,
title: item.title,
author: item.author
};
});
updateDOMElements(existingDOM, virtualDocument);
}
window.setInterval(() => {
let books = [];
for (let i = 0; i < Math.floor(Math.random() * 100); i++) {
books.push({
title: "Book " + (i + 1),
author: "Author " + (i + 1),
id: i + 1
});
}
updateVirtualDocument(books);
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment