Complete the code to create a simple in-memory cache object.
const cache = {};
function setCache(key, value) {
cache[[1]] = value;
}The cache stores values using the key as the property name. So we use key inside the brackets.
Complete the code to check if a key exists in the cache.
function hasCache(key) {
return [1] in cache;
}in incorrectly.To check if a key exists in an object, use the in operator with the key.
Fix the error in the code to retrieve a cached value safely.
function getCache(key) {
if (cache.[1](key)) {
return cache[key];
}
return null;
}includes or indexOf on objects.contains on objects.The hasOwnProperty method checks if the object has the key as its own property, which is safe for cache lookup.
Fill both blanks to implement a cache with expiration time.
const cache = {};
function setCache(key, value, ttl) {
cache[key] = { value: value, expiresAt: Date.now() + [1] };
}
function getCache(key) {
const entry = cache[key];
if (entry && entry.expiresAt > [2]) {
return entry.value;
}
return null;
}Date.now without parentheses, which is a function reference.We add the ttl (time to live) to the current time to set expiration. When getting, we compare expiration with the current time using Date.now().
Fill all three blanks to implement a cache with a cleanup function that removes expired entries.
const cache = {};
function setCache(key, value, ttl) {
cache[key] = { value: value, expiresAt: Date.now() + [1] };
}
function cleanupCache() {
const now = [2];
for (const key in cache) {
if (cache[key].expiresAt <= now) {
[3] cache[key];
}
}
}Date.now without parentheses.The ttl is added to current time to set expiration. We get current time with Date.now(). To remove expired entries, we use the delete operator on the cache property.