Exercise 15: Fetch with Cache Control
Problem Statement
Function `fetchWithCache(url, options, cacheTime)` banao jo response ko cache kare.
Example: fetchWithCache(url, {}, 60000) → caches for 60 seconds
Sample Output:
await fetchWithCache(url, {}, 60000)
// Caches response for 60 secondsSolution
const fetchWithCache = async (url, options = {}, cacheTime = 60000) => {
const cacheKey = `fetch_${url}`;
const cached = sessionStorage.getItem(cacheKey);
if (cached) {
const {data, timestamp} = JSON.parse(cached);
if (Date.now() - timestamp < cacheTime) return new Response(JSON.stringify(data));
}
const res = await fetch(url, options);
const data = await res.json();
sessionStorage.setItem(cacheKey, JSON.stringify({data, timestamp: Date.now()}));
return new Response(JSON.stringify(data));
};Explanation
Overall Goal:
- Fetch response ko cache karna.
Real world:
- Performance: response caching.
- Offline support: cached responses.