/** @template T @typedef {function(): T} FunctionReturning */

/**
* @template T
* @param {FunctionReturning<T>} fn memorized function
* @returns {FunctionReturning<T>} new function
*/
const memoize = fn => {
let cache = false;
/** @type {T} */
let result = undefined;
return () => {
if (cache) {
return result;
} else {
result = fn();
cache = true;
// Allow to clean up memory for fn
// and all dependent resources
fn = undefined;
return result;
}
};
};

测试:

let newFn = memoize(() => {
console.log('执行')
return 'hello'
})

console.log(newFn())
console.log(newFn())

然后升级一下,支持调用内部函数:

/**
* @template {Function} T
* @param {function(): T} factory factory function
* @returns {T} function
*/
const lazyFunction = factory => {
const fac = memoize(factory);
const f = /** @type {any} */ (
(...args) => {
return fac()(...args);
}
);
return /** @type {T} */ (f);
};

测试代码:

let newFn = lazyFunction(() => {
console.log('执行')
return (val) => {
console.log(val)
return val
}
})
console.log(newFn(1))
console.log(newFn(1))