/** * @description 定义惰性单例工厂函数类型。 */ export type SingletonFactory = () => T /** * @description 创建一个会缓存首次结果的单例工厂。 * * @example * ``` * // Scenario 1: object values are created once and then reused. * let calls = 0 * const getConfig = getSingletonFactory(() => { * calls += 1 * return { env: "test" } * }) * * const example1 = getConfig() * const example2 = getConfig() * const example3 = example1 === example2 * const example4 = calls * * // Expect: true * example3 * // Expect: 1 * example4 * * // Scenario 2: primitive values are also cached after the first read. * let count = 0 * const getPort = getSingletonFactory(() => { * count += 1 * return 3000 * }) * * const example5 = getPort() * const example6 = getPort() * const example7 = count * * // Expect: 3000 * example5 * // Expect: 3000 * example6 * // Expect: 1 * example7 * ``` */ export const getSingletonFactory = (make: () => T): SingletonFactory => { let singleton: T | undefined = undefined return () => { if (singleton === undefined) { singleton = make() } return singleton } }