Logos DX
    Preparing search index...

    Function memoizeSync

    • Memoizes a synchronous function with intelligent caching and LRU eviction.

      What it does:

      • Caches sync function results with configurable TTL
      • LRU eviction when cache reaches maxSize
      • Background cleanup of expired entries
      • WeakRef support for memory-sensitive scenarios
      • Zero promise overhead (fully synchronous)

      What it doesn't do:

      • No inflight deduplication (sync functions execute instantly)
      • No async cache adapters (uses direct Map for performance)
      • No stale-while-revalidate (not applicable for sync, use memoize for async)

      When to use:

      • Expensive pure computations (parsing, transformations, calculations)
      • Functions called frequently with the same arguments
      • Need caching without async overhead

      Performance notes:

      • Optimized cache hit path with minimal allocations
      • Direct Map usage (no adapter abstraction overhead)
      • Default key generation: O(n) in argument structure size

      Type Parameters

      • T extends Func<any>

        Sync function type

      Parameters

      • fn: T

        Sync function to memoize

      • opts: MemoizeSyncOptions<T> = {}

        Memoization options (adapter, staleIn, staleTimeout not supported)

      Returns EnhancedMemoizedFunction<T>

      Enhanced memoized function with cache management methods

      // Basic usage
      const fibonacci = (n: number): number => {
      if (n <= 1) return n;
      return fibonacci(n - 1) + fibonacci(n - 2);
      };
      const memoFib = memoizeSync(fibonacci);

      memoFib(40); // Computed once and cached
      memoFib(40); // Instant return from cache
      // With custom key and TTL
      const parseJSON = (str: string) => JSON.parse(str);
      const memoizedParse = memoizeSync(parseJSON, {
      generateKey: (str) => str.substring(0, 100), // Cache by first 100 chars
      ttl: 300000, // 5 minutes
      maxSize: 50
      });
      // Conditional caching - bypass cache for specific calls
      const expensiveCalc = (value: number, opts?: { bustCache?: boolean }) => {
      return value * 2 + Math.random();
      };
      const smartCalc = memoizeSync(expensiveCalc, {
      shouldCache: (value, opts) => !opts?.bustCache,
      ttl: 60000
      });

      // This call uses cache
      smartCalc(42);

      // This call bypasses cache and executes directly
      smartCalc(42, { bustCache: true });