webpack/lib/util/memoize.js

37 lines
681 B
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
2025-03-11 08:28:01 +08:00
/**
* @template T
* @typedef {() => T} FunctionReturning
2025-03-11 08:28:01 +08:00
*/
/**
* @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
2024-10-01 03:05:27 +08:00
/** @type {FunctionReturning<T> | undefined} */
(fn) = undefined;
2024-07-31 04:21:27 +08:00
return /** @type {T} */ (result);
};
};
module.exports = memoize;