Write a function `retryWithBackoff(fn, maxRetries, baseDelay)` that retries an async function with exponential delays (baseDelay * 2^attempt).
Problem Statement
Examples
Input: retryWithBackoff(fetchData, 3, 100)
Output: Data on success, or throws error after 3 retries
Explanation: Retries with delays of 100ms, 200ms, 400ms.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Retry with Exponential Backoff, we consider the execution characteristics of JavaScript engines. Write a function `retryWithBackoff(fn, maxRetries, baseDelay)` that retries an async function with exponential delays (baseDelay * 2^attempt). By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (on each retry, the delay doubles: basedelay, basedelay*2, basedelay*4, etc).
- Implement Logic: Handle state and transformations efficiently (use a loop or recursion with await for the delay).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
async function retryWithBackoff(fn, maxRetries, baseDelay) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt === maxRetries) throw err;
await new Promise(r => setTimeout(r, baseDelay * Math.pow(2, attempt)));
}
}
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.