Creates a memoized version of a function that caches its results based on arguments. Supports both synchronous and asynchronous functions with advanced features like TTL, maximum cache size with LRU eviction, and custom key resolution.
Example:
// Simple memoization for expensive computationconst fibonacci = memoize((n: number): number => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2);});// With TTL and max sizeconst fetchUser = memoize( async (id: string) => { const response = await fetch(`/api/users/${id}`); return response.json(); }, { ttl: 60000, maxSize: 100 } // Cache for 1 minute, max 100 entries);// With custom key resolverconst searchProducts = memoize( (query: string, filters: object) => performSearch(query, filters), { keyResolver: (query, filters) => `${query}-${JSON.stringify(filters)}` });// Cache managementfetchUser.clear(); // Clear all cachefetchUser.delete('user-123'); // Delete specific cache entryconsole.log(fetchUser.size()); // Get cache size Copy
// Simple memoization for expensive computationconst fibonacci = memoize((n: number): number => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2);});// With TTL and max sizeconst fetchUser = memoize( async (id: string) => { const response = await fetch(`/api/users/${id}`); return response.json(); }, { ttl: 60000, maxSize: 100 } // Cache for 1 minute, max 100 entries);// With custom key resolverconst searchProducts = memoize( (query: string, filters: object) => performSearch(query, filters), { keyResolver: (query, filters) => `${query}-${JSON.stringify(filters)}` });// Cache managementfetchUser.clear(); // Clear all cachefetchUser.delete('user-123'); // Delete specific cache entryconsole.log(fetchUser.size()); // Get cache size
The function to memoize. Can be synchronous or asynchronous.
Configuration options for memoization behavior.
A memoized version of the function with cache management methods.
// Fibonacci with memoizationconst fib = memoize((n: number): number => { if (n <= 1) return n; return fib(n - 1) + fib(n - 2);});console.log(fib(40)); // Fast due to memoization Copy
// Fibonacci with memoizationconst fib = memoize((n: number): number => { if (n <= 1) return n; return fib(n - 1) + fib(n - 2);});console.log(fib(40)); // Fast due to memoization
// API call with TTLconst getUser = memoize( async (id: string) => { const res = await fetch(`/api/users/${id}`); return res.json(); }, { ttl: 5000 } // Cache for 5 seconds); Copy
// API call with TTLconst getUser = memoize( async (id: string) => { const res = await fetch(`/api/users/${id}`); return res.json(); }, { ttl: 5000 } // Cache for 5 seconds);
Creates a memoized version of a function that caches its results based on arguments. Supports both synchronous and asynchronous functions with advanced features like TTL, maximum cache size with LRU eviction, and custom key resolution.
Example: