← All Exercises

Latest-Request-Wins Response Gate

advancedjavascript~15min

Background

Users type faster than networks respond, so old responses can overwrite fresh results. Real implementations use AbortController plus a response gate that ignores completions from superseded requests.

Problem

Implement runRequests(events) for a search-as-you-type UI. A start event supersedes the active request, recording its id as aborted. A complete event commits its value only when its id matches the active request; otherwise the id is recorded as stale. Return committed values in completion order plus the aborted and stale id lists.

Input

A JSON object with events, each either start (id) or complete (id, value).

Output

A JSON object with committed values, aborted ids, and stale ids.

Sample tests

Sample 1

Input: {"events":[{"type":"start","id":1},{"type":"start","id":2},{"type":"complete","id":1,"value":"old"},{"type":"complete","id":2,"value":"new"}]}
Expected: {"committed":["new"],"aborted":[1],"stale":[1]}

Sample 2

Input: {"events":[{"type":"start","id":1},{"type":"complete","id":1,"value":"a"},{"type":"start","id":2},{"type":"complete","id":2,"value":"b"}]}
Expected: {"committed":["a","b"],"aborted":[],"stale":[]}

Sample 3

Input: {"events":[{"type":"start","id":1},{"type":"start","id":2},{"type":"complete","id":2,"value":"b"},{"type":"complete","id":1,"value":"a"}]}
Expected: {"committed":["b"],"aborted":[1],"stale":[1]}

Sample 4

Input: {"events":[{"type":"start","id":7},{"type":"start","id":8},{"type":"start","id":9},{"type":"complete","id":9,"value":"z"}]}
Expected: {"committed":["z"],"aborted":[7,8],"stale":[]}

Your solution

Learning objective

Understand request races in browsers, cancellation semantics similar to AbortController, and last-write-wins policies.