memoize.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var cacheProp = Symbol.for('[memoize]');
  4. function Memoize(keyBuilder) {
  5. return function (_, propertyKey, descriptor) {
  6. if (descriptor.value != null) {
  7. descriptor.value = memoize(propertyKey, descriptor.value, keyBuilder || (function (v) { return v; }));
  8. }
  9. else if (descriptor.get != null) {
  10. descriptor.get = memoize(propertyKey, descriptor.get, keyBuilder || (function () { return propertyKey; }));
  11. }
  12. };
  13. }
  14. exports.Memoize = Memoize;
  15. function ensureCache(target, reset) {
  16. if (reset === void 0) { reset = false; }
  17. if (reset || !target[cacheProp]) {
  18. Object.defineProperty(target, cacheProp, {
  19. value: Object.create(null),
  20. configurable: true,
  21. });
  22. }
  23. return target[cacheProp];
  24. }
  25. function ensureChildCache(target, key, reset) {
  26. if (reset === void 0) { reset = false; }
  27. var dict = ensureCache(target);
  28. if (reset || !dict[key]) {
  29. dict[key] = new Map();
  30. }
  31. return dict[key];
  32. }
  33. function memoize(namespace, func, keyBuilder) {
  34. return function () {
  35. var args = [];
  36. for (var _i = 0; _i < arguments.length; _i++) {
  37. args[_i] = arguments[_i];
  38. }
  39. var cache = ensureChildCache(this, namespace);
  40. var key = keyBuilder.apply(this, args);
  41. if (cache.has(key))
  42. return cache.get(key);
  43. var res = func.apply(this, args);
  44. cache.set(key, res);
  45. return res;
  46. };
  47. }