MediumPro challengeJavaScriptTypeScript

Implement Fake Timers

TestingJavaScriptAsyncScheduling

Implement solve(op, ...args) simulating Jest's jest.useFakeTimers():

OpArgsDescription
'setTimeout'(fnBody, delay)Schedule a callback (given as JS source string) after delay ms. Returns timer ID (integer).
'advance'(ms)Advance the fake clock by ms milliseconds. All timers that are due fire in order. Returns list of IDs that fired.
'clearTimeout'(id)Cancel a pending timer. Returns true if it existed, false otherwise.
'runAll'Fire all pending timers immediately (in order of delay). Returns list of IDs that fired.
'pending'Returns count of pending (not yet fired, not cleared) timers.
const t1 = solve('setTimeout', 'log.push(1)', 100)
const t2 = solve('setTimeout', 'log.push(2)', 200)
solve('advance', 150)   // fires t1 → [t1]
solve('pending')        // 1
solve('runAll')         // fires t2 → [t2]
solve('pending')        // 0

Timers share a module-level log array and a currentTime number — you may use these in fnBody strings.

Sample tests

Test #1advance 150ms fires only timer 0
Input: ["advance",150]
Output: [0]
Test #2runAll fires remaining timer
Input: ["runAll"]
Output: [1]
Test #3setTimeout returns timer ID 0
Input: ["setTimeout","log.push(1)",100]
Output: 0
Test #4second setTimeout returns ID 1
Input: ["setTimeout","log.push(2)",200]
Output: 1
Test #5two pending timers
Input: ["pending"]
Output: 2
Test #6one pending timer remaining
Input: ["pending"]
Output: 1