Cache Values with an Expiry Time
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Write createCache(options), a cache whose entries expire, for things like API responses. options may hold maxSize, the most entries it keeps (default: no limit); ttl, how many milliseconds an entry lives (default: forever); and now, a function returning the current time in milliseconds (default: Date.now; the checks pass a fake clock). options may be left out. Return an object with get(key), set(key, value, ttl), has(key), delete(key) and size(). set stores the value, replacing any old one, with the ttl it's given or else the cache's default; an entry set at time t has expired once now() reaches t plus its ttl. get returns a live entry's value, or undefined if the key is missing or expired. has says whether a live entry exists; delete removes the key and returns whether a live entry was there; size counts live entries only. get and set count as uses of an entry, but has doesn't. When a set leaves more than maxSize entries, first drop any that have expired, then, if there are still too many, the least recently used.
Your code must pass
- Stores and returns values
- Expires entries after their time to live
- Lets each entry set its own time to live
- Evicts the least recently used entry when full
- Drops expired entries before fresh ones
- Counts only live entries