memoize.js 678 B

123456789101112131415161718192021222324252627282930313233
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. /** @template T @typedef {function(): T} FunctionReturning */
  6. /**
  7. * @template T
  8. * @param {FunctionReturning<T>} fn memorized function
  9. * @returns {FunctionReturning<T>} new function
  10. */
  11. const memoize = fn => {
  12. let cache = false;
  13. /** @type {T | undefined} */
  14. let result;
  15. return () => {
  16. if (cache) {
  17. return /** @type {T} */ (result);
  18. }
  19. result = fn();
  20. cache = true;
  21. // Allow to clean up memory for fn
  22. // and all dependent resources
  23. /** @type {FunctionReturning<T> | undefined} */
  24. (fn) = undefined;
  25. return /** @type {T} */ (result);
  26. };
  27. };
  28. module.exports = memoize;