Keep Only the Latest Result

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

The problem

  • easy
  • Code

Write latestOnly(fn), where fn returns a promise, like a search request. Return a function that passes its arguments on to fn and returns a promise. A call is overtaken once another call is made after it. The promise of a call that hasn't been overtaken settles like fn's promise for it: it resolves with the same value or rejects with the same reason. An overtaken call must never resolve: reject it with an Error whose name is "StaleError", at the latest when fn's promise for it settles (earlier is fine too). So a slow, older search can never replace the results of a newer one.

Your code must pass

  • Passes the arguments to fn and returns its result
  • Ignores an older result that arrives last
  • Ignores an older result that arrives first
  • Passes the latest call's rejection on