AniUI Academy
hard+350 XPPractice

Cache async results with a TTL

Config, feature flags and the current user are read constantly and change rarely. Caching them for a few seconds removes most of the requests, as long as concurrent callers share one load and errors are not remembered.

Implement createCache(loader, ttl), returning an object with get(key) and invalidate(key). On a miss, get calls loader(key) and returns its promise. While that load is in flight, further get calls for the same key return the same promise without calling loader again. Once it fulfils, the value is served for ttl milliseconds measured from when it fulfilled; after that the next get loads again. If the loader rejects, the rejection is passed to the waiting callers and nothing is stored, so the next get retries. invalidate(key) drops any entry for that key so the next get reloads.

What it has to do

  • Call loader once for a key and reuse the value until the TTL expires.
  • Share one in-flight load between concurrent get calls for the same key.
  • Reload after the TTL has elapsed.
  • Never cache a rejection: the next get must call loader again.
  • Make invalidate(key) force the next get to reload.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.