Back to Snippets
TypeScript

Generic Memoization Function

Description

Caches function results based on arguments to avoid redundant computations

Code

/**
 * Generic memoization function
 * @param fn Function to memoize
 * @returns Memoized function
 */
function memoize<T extends (...args: any[]) => any>(fn: T): T {
  const cache = new Map<string, ReturnType<T>>();
  
  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const key = JSON.stringify(args);
    
    if (cache.has(key)) {
      return cache.get(key);
    }
    
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  } as T;
}

// Usage Example
// Expensive computation function
const fibonacci = memoize((n: number): number => {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
});

console.log(fibonacci(10)); // Computed and cached
console.log(fibonacci(10)); // Returned from cache (much faster)

// With object arguments
const getUserData = memoize(async (userId: number, options: { details: boolean }) => {
  const response = await fetch(`https://api.example.com/users/${userId}`);
  return response.json();
});

Usage

Perfect for optimizing expensive computations, API calls, or any function with repeated identical calls

Tags

PerformanceMemoizationCachingTypeScript