Exercise 18: Function Retry Wrapper

Problem Statement

Create a function `withRetry(fn, maxAttempts)` that retries function on failure.

Sample Output:

const retried = withRetry(async () => fetchAPI(), 3);
await retried() => (retries up to 3 times on failure)

Solution

const withRetry = (fn, maxAttempts = 3) => {
  return async (...args) => {
    let lastError;
    for (let i = 0; i < maxAttempts; i++) {
      try { return await fn(...args); }
      catch (err) { lastError = err; }
    }
    throw lastError;
  };
};

Explanation

Overall Goal:

  • Function ko retry wrapper se wrap karna.

Real world:

  • Network calls: retry on failure.
  • Unreliable operations: automatic retry.