happy-rusty
    Preparing search index...

    Function Lazy

    • Creates a new Lazy<T> with the given synchronous initialization function.

      The function is called at most once, on first access via force().

      Type Parameters

      • T

        The type of value to store.

      Parameters

      • fn: () => T

        The initialization function that produces the value.

      Returns Lazy<T>

      A new Lazy<T> instance.

      // Basic usage
      const lazy = Lazy(() => {
      console.log('Initializing');
      return 42;
      });

      console.log(lazy.isInitialized()); // false
      console.log(lazy.force()); // logs "Initializing", returns 42
      console.log(lazy.isInitialized()); // true
      console.log(lazy.force()); // returns 42 (no log)
      // Lazy singleton pattern
      const logger = Lazy(() => new Logger('app'));

      function getLogger(): Logger {
      return logger.force();
      }
      // Expensive computation
      const fibonacci = Lazy(() => {
      function fib(n: number): number {
      if (n <= 1) return n;
      return fib(n - 1) + fib(n - 2);
      }
      return fib(40); // Only computed once
      });