memoize.js 679 B

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