TS-Scribe - v0.6.2
    Preparing search index...

    Function memoize

    • 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 computation
      const fibonacci = memoize((n: number): number => {
      if (n <= 1) return n;
      return fibonacci(n - 1) + fibonacci(n - 2);
      });

      // With TTL and max size
      const 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 resolver
      const searchProducts = memoize(
      (query: string, filters: object) => performSearch(query, filters),
      { keyResolver: (query, filters) => `${query}-${JSON.stringify(filters)}` }
      );

      // Cache management
      fetchUser.clear(); // Clear all cache
      fetchUser.delete('user-123'); // Delete specific cache entry
      console.log(fetchUser.size()); // Get cache size

      Type Parameters

      • Args extends unknown[]
      • ReturnType

      Parameters

      • fn: (...args: Args) => ReturnType

        The function to memoize. Can be synchronous or asynchronous.

      • options: MemoizeOptions<Args> = {}

        Configuration options for memoization behavior.

      Returns MemoizedFunction<Args, ReturnType>

      A memoized version of the function with cache management methods.

      // Fibonacci with memoization
      const 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 TTL
      const getUser = memoize(
      async (id: string) => {
      const res = await fetch(`/api/users/${id}`);
      return res.json();
      },
      { ttl: 5000 } // Cache for 5 seconds
      );