memoize.js 711 B

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