Implement a circuit breaker that opens after `threshold` failures. When open, it immediately fails without calling the function. Resets after `resetTimeout` ms.
Problem Statement
Implement a circuit breaker that opens after `threshold` failures. When open, it immediately fails without calling the function. Resets after `resetTimeout` ms.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
States: CLOSED (normal), OPEN (failing fast), HALF_OPEN (testing).
š” Hint 2:
Track failure count. When it reaches threshold, switch to OPEN.
š” Hint 3:
In OPEN state, check if resetTimeout has elapsed to move to HALF_OPEN and try again.
ā
Solution:
```javascript
function createCircuitBreaker(fn, threshold, resetTimeout) {
let failures = 0;
let state = "CLOSED";
let lastFailTime = 0;
return {
call(...args) {
if (state === "OPEN") {
if (Date.now() - lastFailTime >= resetTimeout) {
state = "HALF_OPEN";
} else {
throw new Error("Circuit is OPEN");
}
}
try {
const result = fn(...args);
failures = 0;
state = "CLOSED";
return result;
} catch (e) {
failures++;
lastFailTime = Date.now();
if (failures >= threshold) state = "OPEN";
throw e;
}
},
getState() { return state; }
};
}
```