const apiCache = new Map(); // Stores { url: { data, timestamp } } const CACHE_DURATION_MS = 5 * 60 * 1000; // 5 minutes async function fetchWithCache(url, options = {}) { const now = Date.now(); if (apiCache.has(url)) { const cachedEntry = apiCache.get(url); if (now - cachedEntry.timestamp < CACHE_DURATION_MS) { console.log(`Serving from cache: ${url}`); return cachedEntry.data; } else { console.log(`Cache expired for: ${url}`); apiCache.delete(url); // Remove expired entry } } console.log(`Fetching from API: ${url}`); try { const response = await fetch(url, options); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); apiCache.set(url, { data, timestamp: now }); return data; } catch (error) { console.error('Error fetching data:', error); throw error; } } // Example usage: // (async () => { // const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1'; // await fetchWithCache(apiUrl).then(data => console.log('First fetch:', data)); // // Subsequent call within cache duration will serve from cache // await fetchWithCache(apiUrl).then(data => console.log('Second fetch (cached):', data)); // })();