Implement a memoize function that caches the results of asynchronous function calls and does not send a duplicate request if a call with the same arguments has already been made.
sobes.tech AI
Answer from AI
javascript function memoize(asyncFunc) { const cache = new Map();
return async function(...args) { const key = JSON.stringify(args); if (cache.has(key)) { return cache.get(key); } const promise = asyncFunc(...args); cache.set(key, promise); try { const result = await promise; // You can update the cache with the result if you want to store the actual result instead of the promise return result; } catch (error) { cache.delete(key); // Remove from cache on error to retry throw error; } }; }
// Example usage:
async function fetchData(id) {
console.log('Fetching', id);
return new Promise(resolve => setTimeout(() => resolve(Data for ${id}), 1000));
}
const memoizedFetch = memoize(fetchData);
memoizedFetch(1).then(console.log); // Request will be sent memoizedFetch(1).then(console.log); // Will return from cache
In this example, the cache stores promises so that repeated calls with the same arguments do not re-run the function but return the already executing or completed promise.