Share In-Flight Requests per Key, Typed

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write memoizeAsync(fn), where fn takes one string or number key and returns a promise. Calls with the same key share one promise, whether the first call is still running or has already resolved, so fn runs once per key; a call that rejects is forgotten, so the next call for that key tries again. Type it so the returned function keeps fn's key and resolved types, and a key that isn't a string or number is rejected.

Your code must pass

  • Shares one call per key
  • Keeps the result after it resolves
  • Forgets a failed call
  • Has no type errors
  • Keeps fn's key type
  • Keeps fn's resolved type
  • Rejects keys that aren't strings or numbers