/**
 * lazy.ts — per-request memoized factory helper.
 *
 * Creates a zero-argument getter that invokes the factory exactly once,
 * memoizes the result, and returns it on every subsequent call.
 *
 * Worker-isolate safe: the closure lives on the stack of a single request
 * handler and is GC'd when `locals` is released.
 *
 * Usage:
 *   const getDb = lazy(() => buildDb(env));
 *   const db = factory(); // constructed on first call
 *   const db2 = factory(); // same instance
 */

/**
 * Returns a memoized factory getter. The factory is invoked at most once.
 */
export function lazy<T>(factory: () => T): () => T {
  let instance: T | undefined;
  let initialized = false;
  return (): T => {
    if (!initialized) {
      instance = factory();
      initialized = true;
    }
    return instance as T;
  };
}
