Skip to main content

Promise Cache

MIDDLE

Promise Cache

Create a cache wrapper for async functions to avoid redundant calls.

Requirements:

  • Implement promiseCache that wraps an async function
  • Cache results by function arguments
  • If same arguments used again, return cached result
  • Support cache invalidation
  • Handle errors properly (don't cache errors)

Example:

let callCount = 0;
const fetchUser = async (id) => {
  callCount++;
  return { id, name: `User${id}` };
};

const cachedFetch = promiseCache(fetchUser);

await cachedFetch(1); // Calls fetchUser
await cachedFetch(1); // Returns cached result
console.log(callCount); // 1

Examples:

Input 1:{"args":[5]}
Output 1:10
Input 2:{"args":[10]}
Output 2:11

Loading editor...

Run your code to see results

Click the Run button above