cache.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. /**
  3. * Creates a cache that evicts keys in fifo order
  4. * @param size {Number}
  5. */
  6. function makeFifoCache(
  7. size,
  8. )
  9. {
  10. // Maintain a fifo queue of keys, we cannot rely on Object.keys as the browser may not support it.
  11. let evictionOrder = [];
  12. let cache = {};
  13. return {
  14. add(key, value) {
  15. while (evictionOrder.length >= size) {
  16. // shift is O(n) but this is small size and only happens if we are
  17. // exceeding the cache size so it should be fine.
  18. const evictCandidate = evictionOrder.shift();
  19. if (evictCandidate !== undefined) {
  20. // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
  21. delete cache[evictCandidate];
  22. }
  23. }
  24. // in case we have a collision, delete the old key.
  25. if (cache[key]) {
  26. this.delete(key);
  27. }
  28. evictionOrder.push(key);
  29. cache[key] = value;
  30. },
  31. clear() {
  32. cache = {};
  33. evictionOrder = [];
  34. },
  35. get(key) {
  36. return cache[key];
  37. },
  38. size() {
  39. return evictionOrder.length;
  40. },
  41. // Delete cache key and return true if it existed, false otherwise.
  42. delete(key) {
  43. if (!cache[key]) {
  44. return false;
  45. }
  46. // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
  47. delete cache[key];
  48. for (let i = 0; i < evictionOrder.length; i++) {
  49. if (evictionOrder[i] === key) {
  50. evictionOrder.splice(i, 1);
  51. break;
  52. }
  53. }
  54. return true;
  55. },
  56. };
  57. }
  58. exports.makeFifoCache = makeFifoCache;
  59. //# sourceMappingURL=cache.js.map