LRU cache
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a cache object that holds at most `capacity` entries (`capacity` is at least 1) with three methods. `get(key)` returns the stored value, or `undefined` when the key is missing, and marks the key as the most recently used. `set(key, value)` stores or replaces the value and marks the key as the most recently used; when the cache then holds more than `capacity` entries, the least recently used key is removed. `keys()` returns an array of the keys from least to most recently used. Values such as `0`, `false` and `null` are stored and returned like any other, and `1` and `"1"` are different keys.
What this exercise teaches
Deleting and re-inserting moves a key to the end of a Map, which turns the Map's insertion order into recency order for free. Checking has() keeps falsy values working, and get must refresh too, otherwise a key that is read often is still the first to go.
A hint if you get stuck
A `Map` remembers insertion order. To mark a key as most recent, delete it and set it again; the least recently used key is then `map.keys().next().value`. Use `map.has(key)` rather than testing the value.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Async and functions
- A counter with private stateFree
- Sleep with a PromiseFree
- Retry a failing callFree
- Promise.all with a concurrency limitFree
- DebounceFree
- MemoizeFree
- Run only onceFree
- Pipe functions togetherFree
- Timeout wrapperFree
- Run tasks in sequenceFree
- ThrottleFree
- Curry a functionFree
- Event emitterFree
- Write your own Promise.allFree
- Callback style to a PromiseFree