memoizeCapped.cjs 2.1 KB

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