Write a function `retry(fn, maxRetries)` that retries a function up to maxRetries times with exponential backoff delays (simulated).
Problem Statement
Write a function `retry(fn, maxRetries)` that retries a function up to maxRetries times with exponential backoff delays (simulated).
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Exponential backoff doubles the delay after each failure.
š” Hint 2:
Catch errors and retry until maxRetries is exhausted.
š” Hint 3:
Use a loop with try/catch. Track attempt count.
ā
Solution:
```javascript
function retry(fn, maxRetries) {
let attempts = 0;
while (attempts <= maxRetries) {
try {
return fn(attempts);
} catch (e) {
attempts++;
if (attempts > maxRetries) throw e;
}
}
}
```