cache.js 1.5 KB

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