// Created on savesnippets.com · https://savesnippets.com/Jvba8zV4CJ6AJK export function lazy(factory: () => T): () => T { let cached: T | undefined; let initialized = false; return () => { if (!initialized) { cached = factory(); initialized = true; } return cached as T; }; } // Module-scoped lazy singleton — DB connection const getDb = lazy(() => { console.log('Connecting to DB…'); // logged exactly once return new DatabaseClient(process.env.DATABASE_URL!); }); // Anywhere in the codebase: const db = getDb(); // first call: opens connection const db2 = getDb(); // subsequent calls: returns the same instance