Fix the request settling in a React search hook
Your task
An AI agent wrote a React hook that debounces a search box and fetches results. A reviewer asks what happens when a slow early response arrives after a newer one, or after the component unmounts. You model the hook as a list of events and decide which responses it renders.
An assistant wrote apply_search_results(events). It is in the editor. It has a bug. Find it and fix it.
Input and output:
events: the events in arrival order. Each is"request|<seq>","response|<seq>|<payload>"or"unmount".- Return the payloads the hook renders, in order.
Rules the tests check:
- Split each event on
|. Ignore an event that is not exactly one of the three shapes:unmountalone,requestwith 1 more part, orresponsewith 2 more parts. <seq>must be one or more digits from 0 to 9, or the event is ignored. Sequence numbers compare as numbers, so007equals7.- The hook tracks one in-flight number, which starts at 0. A request sets it to its sequence number, whatever the number is.
- After
unmount, nothing renders again. - While mounted, a response renders when its sequence number equals the in-flight number. Rendering settles the request: the in-flight number goes back to 0.
- Any other response is ignored.
Examples
apply_search_results(events: list[str]) -> list[str]Example 1
Input
apply_search_results(["request|1", "response|1|apple"])Output
["apple"]Example 2
Input
apply_search_results(["request|1", "request|2", "response|1|old", "response|2|new"])Output
["new"]Example 3
Input
apply_search_results(["request|1", "unmount", "response|1|late"])Output
[]