Implementing a Simple In-Memory Cache
Demonstrate setting up a simple in-memory caching mechanism using a JavaScript object to store and retrieve data.
/* HTML structure */
<div id="cacheOutput"></div>
HTML container where cached data output will be displayed.
/* CSS styles */
#cacheOutput {
font-family: 'Arial', sans-serif;
margin: 10px;
padding: 5px;
border: 1px solid #ddd;
}
Styling for the div where cached data will be shown.
/* JavaScript Cache Implementation */
const cache = {};
function writeToCache(key, value) {
cache[key] = value;
}
function readFromCache(key) {
return cache[key];
}
function displayCachedData(key) {
const outputDiv = document.getElementById('cacheOutput');
const data = readFromCache(key);
outputDiv.textContent = data ? `Cached Data: ${data}` : 'No data in cache.';
}
// Example Usage
writeToCache('user', JSON.stringify({ name: 'Alice', age: 30 }));
displayCachedData('user');
JavaScript functions to implement in-memory caching. writeToCache stores data in the cache, readFromCache retrieves data from the cache, and displayCachedData updates the HTML with the cached data.