memoize.js 766 B

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