webpack/lib/util/memoize.js

33 lines
626 B
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
/** @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;
2023-06-12 22:21:21 +08:00
/** @type {T | undefined} */
2024-07-31 06:15:03 +08:00
let result;
return () => {
if (cache) {
2023-06-12 22:21:21 +08:00
return /** @type {T} */ (result);
}
2024-07-31 04:21:27 +08:00
result = fn();
cache = true;
// Allow to clean up memory for fn
// and all dependent resources
fn = undefined;
return /** @type {T} */ (result);
};
};
module.exports = memoize;