memorize.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. const cacheStore = new WeakMap();
  3. // eslint-disable-next-line jsdoc/no-restricted-syntax
  4. /**
  5. * @template T
  6. * @typedef {(...args: any) => T} FunctionReturning
  7. */
  8. /**
  9. * @template T
  10. * @param {FunctionReturning<T>} fn memorized function
  11. * @param {({ cache?: Map<string, { data: T }> } | undefined)=} cache cache
  12. * @param {((value: T) => T)=} callback callback
  13. * @returns {FunctionReturning<T>} new function
  14. */
  15. function memorize(fn, {
  16. cache = new Map()
  17. } = {}, callback = undefined) {
  18. // eslint-disable-next-line jsdoc/no-restricted-syntax
  19. /**
  20. * @param {any} arguments_ args
  21. * @returns {any} result
  22. */
  23. const memoized = (...arguments_) => {
  24. const [key] = arguments_;
  25. const cacheItem = cache.get(key);
  26. if (cacheItem) {
  27. return cacheItem.data;
  28. }
  29. // @ts-expect-error
  30. let result = fn.apply(this, arguments_);
  31. if (callback) {
  32. result = callback(result);
  33. }
  34. cache.set(key, {
  35. data: result
  36. });
  37. return result;
  38. };
  39. cacheStore.set(memoized, cache);
  40. return memoized;
  41. }
  42. module.exports = memorize;