Only the latest response
Implement latestOnly(fn). fn returns a promise. Every call runs fn, but only the newest call's promise resolves with fn's result: when an older call finishes after a newer one has started, its promise resolves with undefined. This is how a search box ignores a slow, stale response. In the tests a call is [time, duration, value], and each outcome is [status, value, time] in call order.
Start from
function latestOnly(fn) {
// Return a function whose stale calls resolve with undefined.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Give every call a number from a counter in the closure.
Hint 2
After awaiting fn, compare the call's number with the counter. Only the newest call returns the result.
Solution
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function latestOnly(fn) {
let latest = 0;
return async function (...args) {
const id = ++latest;
const result = await fn.apply(this, args);
return id === latest ? result : undefined;
};
}What an interviewer looks for
The out-of-order response is the classic search and autocomplete bug. Interviewers want you to name it and to know both fixes: ignore the stale result, or cancel the request.