Day 48

Memoization

11 min
JavaScript 100 Days

Memoization ek optimization technique hai jahan function ke results cache karte hain. Agar same arguments dobara diye to cached result return karo — function dobara calculate na kare.

Memoize Function

Generic memoization wrapper banao.

memoize.js
javascript
function memoize(fn) {
  const cache = new Map();
  
  return function(...args) {
    const key = JSON.stringify(args);
    
    if (cache.has(key)) {
      console.log("📦 Cache hit!");
      return cache.get(key);
    }
    
    console.log("🔄 Computing...");
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

// Expensive function
function slowFibonacci(n) {
  if (n <= 1) return n;
  return slowFibonacci(n - 1) + slowFibonacci(n - 2);
}

const fastFib = memoize(slowFibonacci);

console.time("first call");
console.log(fastFib(40)); // slow
console.timeEnd("first call");

console.time("second call");
console.log(fastFib(40)); // instant — from cache!
console.timeEnd("second call");

🎯 Practice Challenge

API calls memoize karo with TTL (time-to-live). Cache 5 minutes ke baad expire ho — fresh data fetch ho.