memoize.js 722 B

12345678910111213141516171819202122232425262728293031323334
  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 = undefined;
  15. return () => {
  16. if (cache) {
  17. return /** @type {T} */ (result);
  18. } else {
  19. result = fn();
  20. cache = true;
  21. // Allow to clean up memory for fn
  22. // and all dependent resources
  23. // eslint-disable-next-line no-warning-comments
  24. // @ts-ignore
  25. fn = undefined;
  26. return /** @type {T} */ (result);
  27. }
  28. };
  29. };
  30. module.exports = memoize;