memoizeCapped.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // @ts-nocheck
  2. /**
  3. * Creates a function that memoizes the result of `func`. If `resolver` is
  4. * provided, it determines the cache key for storing the result based on the
  5. * arguments provided to the memoized function. By default, the first argument
  6. * provided to the memoized function is used as the map cache key. The `func`
  7. * is invoked with the `this` binding of the memoized function.
  8. *
  9. * **Note:** The cache is exposed as the `cache` property on the memoized
  10. * function. Its creation may be customized by replacing the `memoize.Cache`
  11. * constructor with one whose instances implement the
  12. * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
  13. * method interface of `clear`, `delete`, `get`, `has`, and `set`.
  14. *
  15. * @since 0.1.0
  16. * @category Function
  17. * @param {Function} func The function to have its output memoized.
  18. * @param {Function} [resolver] The function to resolve the cache key.
  19. * @returns {Function} Returns the new memoized function.
  20. * @example
  21. *
  22. * const object = { 'a': 1, 'b': 2 }
  23. * const other = { 'c': 3, 'd': 4 }
  24. *
  25. * const values = memoize(values)
  26. * values(object)
  27. * // => [1, 2]
  28. *
  29. * values(other)
  30. * // => [3, 4]
  31. *
  32. * object.a = 2
  33. * values(object)
  34. * // => [1, 2]
  35. *
  36. * // Modify the result cache.
  37. * values.cache.set(object, ['a', 'b'])
  38. * values(object)
  39. * // => ['a', 'b']
  40. *
  41. * // Replace `memoize.Cache`.
  42. * memoize.Cache = WeakMap
  43. */
  44. function memoize(func, resolver) {
  45. if (typeof func !== "function" ||
  46. (resolver != null && typeof resolver !== "function")) {
  47. throw new TypeError("Expected a function");
  48. }
  49. const memoized = function (...args) {
  50. const key = resolver ? resolver.apply(this, args) : args[0];
  51. const cache = memoized.cache;
  52. if (cache.has(key)) {
  53. return cache.get(key);
  54. }
  55. const result = func.apply(this, args);
  56. memoized.cache = cache.set(key, result) || cache;
  57. return result;
  58. };
  59. memoized.cache = new (memoize.Cache || Map)();
  60. return memoized;
  61. }
  62. memoize.Cache = Map;
  63. export default memoize;