Description
In web applications, making repeated API calls to the same endpoint can be inefficient and slow down your app.
To improve performance, developers often use caching — storing responses temporarily and reusing them for a short period.
In this challenge, you’ll create a Cached API Wrapper, a function that caches API responses for a specified duration.
This technique helps reduce redundant network requests and mimics how frameworks and data-fetching libraries optimize performance under the hood.
Your Task
Implement a function cachedApi(timer) that returns another asynchronous function responsible for:
- Fetching data from the provided URL.
- Caching the response in memory.
- Returning cached data if the same URL is requested again before the cache expires.
- Automatically removing the cache after the given time.
- Handling errors gracefully.
Method
| Function | Description | 
|---|---|
| 
 | Returns a function that wraps  | 
Example
Input
const fetchWithCache = cachedApi(3000);
(async () => {
  const data1 = await fetchWithCache("https://jsonplaceholder.typicode.com/todos/1");
  console.log("First fetch:", data1);
  const data2 = await fetchWithCache("https://jsonplaceholder.typicode.com/todos/1");
  console.log("Second fetch (cached):", data2);
  setTimeout(async () => {
    const data3 = await fetchWithCache("https://jsonplaceholder.typicode.com/todos/1");
    console.log("Third fetch (after cache expired):", data3);
  }, 4000);
})();
Expected Output
First fetch: { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
Second fetch (cached): { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
Third fetch (after cache expired): { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
Expected Behavior
✅ Caches each API response for the given time
✅ Returns cached result for repeated calls within cache duration
✅ Automatically removes expired cache entries
✅ Handles fetch failures safely
Hints
Hint 1
💡 Use an object or Map to store cached results, using URLs as keys.
Hint 2
Use setTimeout to delete cached data after the given duration.