cache.js 990 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Uses a LRU cache to make a given parametrized function cached.
  3. * Caches just the last value.
  4. * The key must be JSON serializable.
  5. */
  6. export class LRUCachedFunction {
  7. constructor(fn) {
  8. this.fn = fn;
  9. this.lastCache = undefined;
  10. this.lastArgKey = undefined;
  11. }
  12. get(arg) {
  13. const key = JSON.stringify(arg);
  14. if (this.lastArgKey !== key) {
  15. this.lastArgKey = key;
  16. this.lastCache = this.fn(arg);
  17. }
  18. return this.lastCache;
  19. }
  20. }
  21. /**
  22. * Uses an unbounded cache (referential equality) to memoize the results of the given function.
  23. */
  24. export class CachedFunction {
  25. get cachedValues() {
  26. return this._map;
  27. }
  28. constructor(fn) {
  29. this.fn = fn;
  30. this._map = new Map();
  31. }
  32. get(arg) {
  33. if (this._map.has(arg)) {
  34. return this._map.get(arg);
  35. }
  36. const value = this.fn(arg);
  37. this._map.set(arg, value);
  38. return value;
  39. }
  40. }