memoize.js 604 B

1234567891011121314151617181920212223242526272829303132
  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} */
  14. let result = undefined;
  15. return () => {
  16. if (cache) {
  17. return result;
  18. } else {
  19. result = fn();
  20. cache = true;
  21. // Allow to clean up memory for fn
  22. // and all dependent resources
  23. fn = undefined;
  24. return result;
  25. }
  26. };
  27. };
  28. module.exports = memoize;