Fix the stale response guard for a search box

Review the AI's codeEasy12 min

Your task

Your search box sends a request as the user types. When they type fast, an older response sometimes arrives after a newer one and overwrites the results. An AI first "fixed" this by lowering the debounce delay, which changes how often requests fire, not the order responses arrive in. The real fix is a guard on responses.

An assistant wrote apply_search_responses(events), which replays an event log through that guard. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • events: what happened, in order. fire <query> sends a request for the query. resolve <id> is the response to request id arriving.
  • Return the queries whose results are shown, in the order they are shown.

Rules the tests check:

  • An event that starts with fire fires a request for the rest of the text, which can be empty. Requests get ids 0, 1, 2 and so on, in the order they fire.
  • For an event that starts with resolve , the rest is the id. Ignore it unless the id is one or more digits from 0 to 9 and a request with that id has already fired.
  • Show a response only when its id is greater than the id of every response already shown. Otherwise it is stale: drop it.
  • Ignore every other event.

Examples

apply_search_responses(events: list[str]) -> list[str]
Example 1
Inputapply_search_responses(["fire ca", "fire cat", "resolve 1", "resolve 0"])
Output["cat"]
Example 2
Inputapply_search_responses(["fire ca", "resolve 0", "fire cat", "resolve 1"])
Output["ca", "cat"]
Example 3
Inputapply_search_responses(["fire a", "fire ab", "fire abc", "resolve 2", "resolve 1", "resolve 0"])
Output["abc"]