LruCache.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.LruCache = void 0;
  4. class LruCache {
  5. constructor(limit = 1000) {
  6. this.limit = limit;
  7. this.head = undefined;
  8. this.tail = undefined;
  9. this.map = Object.create(null);
  10. this.capacity = limit | 0;
  11. }
  12. get size() {
  13. return this.limit - this.capacity;
  14. }
  15. set(key, value) {
  16. const node = this.map[key];
  17. if (node) {
  18. this.pop(node);
  19. node.v = value;
  20. this.push(node);
  21. }
  22. else {
  23. if (!this.capacity) {
  24. const head = this.head;
  25. if (head) {
  26. this.pop(head);
  27. delete this.map[head.k];
  28. this.capacity++;
  29. }
  30. }
  31. this.capacity--;
  32. const node = new LruNode(key, value);
  33. this.map[key] = node;
  34. this.push(node);
  35. }
  36. }
  37. get(key) {
  38. const node = this.map[key];
  39. if (!node)
  40. return;
  41. if (this.tail !== node) {
  42. this.pop(node);
  43. this.push(node);
  44. }
  45. return node.v;
  46. }
  47. peek(key) {
  48. const node = this.map[key];
  49. return node instanceof LruNode ? node.v : undefined;
  50. }
  51. has(key) {
  52. return key in this.map;
  53. }
  54. clear() {
  55. this.head = undefined;
  56. this.tail = undefined;
  57. this.map = Object.create(null);
  58. this.capacity = this.limit;
  59. }
  60. keys() {
  61. return Object.keys(this.map);
  62. }
  63. del(key) {
  64. const node = this.map[key];
  65. if (node instanceof LruNode) {
  66. this.pop(node);
  67. delete this.map[key];
  68. ++this.capacity;
  69. return true;
  70. }
  71. return false;
  72. }
  73. pop(node) {
  74. const l = node.l;
  75. const r = node.r;
  76. if (this.head === node)
  77. this.head = r;
  78. else
  79. l.r = r;
  80. if (this.tail === node)
  81. this.tail = l;
  82. else
  83. r.l = l;
  84. // node.l = undefined;
  85. // node.r = undefined;
  86. }
  87. push(node) {
  88. const tail = this.tail;
  89. if (tail) {
  90. tail.r = node;
  91. node.l = tail;
  92. }
  93. else
  94. this.head = node;
  95. this.tail = node;
  96. }
  97. }
  98. exports.LruCache = LruCache;
  99. class LruNode {
  100. constructor(k, v) {
  101. this.k = k;
  102. this.v = v;
  103. this.l = undefined;
  104. this.r = undefined;
  105. }
  106. }