Cache with expiry
Implement createCache(ttlMs). It returns { set(key, value), get(key), has(key), delete(key) }. An entry expires ttlMs milliseconds after it was set; read the time with Date.now(). get returns undefined for a missing or expired entry, and has returns false. Setting a key again restarts its time. A stored 0 or empty string is still a hit. In the tests an operation is [time, name, key, value]; the answer lists what each get and has returned.
Start from
function createCache(ttlMs) {
// Return { set, get, has, delete } with entries that expire.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Store the value together with the time it expires: Date.now() + ttlMs.
Hint 2
Write one helper that returns the live entry or undefined, deleting an expired one. Build get and has on it.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function createCache(ttlMs) {
const entries = new Map();
const live = (key) => {
const entry = entries.get(key);
if (!entry) return undefined;
if (Date.now() >= entry.expires) {
entries.delete(key);
return undefined;
}
return entry;
};
return {
set(key, value) {
entries.set(key, { value, expires: Date.now() + ttlMs });
},
get(key) {
return live(key)?.value;
},
has(key) {
return live(key) !== undefined;
},
delete(key) {
return entries.delete(key);
},
};
}What an interviewer looks for
Client-side caching of API data starts here. Interviewers follow up with staleness: who decides the lifetime, and how is the cache cleared after a write?