An app asks the server for the same exchange rates, user profile or search results again and again. Keeping each answer for a while saves the requests, but data that never expires turns stale. A TTL cache (time to live) keeps each entry for a fixed time and then treats it as gone.
classTtlCache {constructor(defaultTtl) // ms; a positive number or Infinity (the default)set(key, value, ttl) // ttl defaults to defaultTtl; returns the cacheget(key) // the value, or undefined when missing or expiredhas(key) // true for a live entrydelete(key) // true when a live entry was removedgetsize() // the number of live entriesprune() // removes expired entries; returns how manyclear() // removes everything}
defaultTtl and any ttl passed to set must be a positive number or Infinity; anything else (0, negative, NaN, a string, null) throws RangeError, and a rejected set stores nothing.
set stores the value with an expiry time of now plus the ttl, and returns the cache so calls can be chained.
An entry is live until now >= expiry time: still there 1 ms before its ttl, gone at the ttl.
A ttl given to set overrides the default. Setting a key again replaces the value and restarts its time. Reading never extends it.
get returns undefined for a missing or expired key.
has is true for any live entry, also one whose value is undefined.
delete removes the entry and returns true only if it was live.
size counts live entries only; prune removes the expired ones and returns how many.
Expired entries do not stay in memory once they have been looked at, counted or pruned.
Keys can be any value and are compared like Map keys (objects by identity, NaN equals NaN, 0 equals -0, "1" differs from 1).
No timers: expiry is checked when an entry is used.
constcache=newTtlCache(1000);cache.set("token", "abc", 50); // this entry: 50 mscache.set("none", undefined);cache.has("none"); // truecache.get("none"); // undefined, but it is there
JAVASCRIPT
newTtlCache(0); // RangeErrornewTtlCache().set("k", 1).get("k"); // 1, and it never expires