memorize.js 787 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. const cacheStore = new WeakMap();
  3. /**
  4. * @template T
  5. * @param {Function} fn
  6. * @param {{ cache?: Map<string, { data: T }> } | undefined} cache
  7. * @param {((value: T) => T)=} callback
  8. * @returns {any}
  9. */
  10. function memorize(fn, {
  11. cache = new Map()
  12. } = {}, callback) {
  13. /**
  14. * @param {any} arguments_
  15. * @return {any}
  16. */
  17. const memoized = (...arguments_) => {
  18. const [key] = arguments_;
  19. const cacheItem = cache.get(key);
  20. if (cacheItem) {
  21. return cacheItem.data;
  22. }
  23. // @ts-ignore
  24. let result = fn.apply(this, arguments_);
  25. if (callback) {
  26. result = callback(result);
  27. }
  28. cache.set(key, {
  29. data: result
  30. });
  31. return result;
  32. };
  33. cacheStore.set(memoized, cache);
  34. return memoized;
  35. }
  36. module.exports = memorize;