MediumPro challengeJavaScriptTypeScript

Batched State Updates

ReactStateBatching

Implement createBatcher(commitFn) returning { schedule, flush }:

  • schedule(update) queues an update.
  • flush() applies all queued updates in one commitFn(updates) call and clears the queue.

solve(events) drives the batcher. Events are 'schedule:N' or 'flush'.
Returns the list of commit calls.

Sample tests

Test #1Two updates, one flush
Input: [["schedule:1","schedule:2","flush"]]
Output: [[1,2]]
Test #2Two batches
Input: [["schedule:1","flush","schedule:2","flush"]]
Output: [[1],[2]]
Test #3Flush with empty queue
Input: [["flush"]]
Output: []
Test #4Schedule without flush
Input: [["schedule:1"]]
Output: []
Test #5Second flush is no-op
Input: [["schedule:1","schedule:2","schedule:3","flush","flush"]]
Output: [[1,2,3]]