LRU.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. var Entry = (function () {
  2. function Entry(val) {
  3. this.value = val;
  4. }
  5. return Entry;
  6. }());
  7. export { Entry };
  8. var LinkedList = (function () {
  9. function LinkedList() {
  10. this._len = 0;
  11. }
  12. LinkedList.prototype.insert = function (val) {
  13. var entry = new Entry(val);
  14. this.insertEntry(entry);
  15. return entry;
  16. };
  17. LinkedList.prototype.insertEntry = function (entry) {
  18. if (!this.head) {
  19. this.head = this.tail = entry;
  20. }
  21. else {
  22. this.tail.next = entry;
  23. entry.prev = this.tail;
  24. entry.next = null;
  25. this.tail = entry;
  26. }
  27. this._len++;
  28. };
  29. LinkedList.prototype.remove = function (entry) {
  30. var prev = entry.prev;
  31. var next = entry.next;
  32. if (prev) {
  33. prev.next = next;
  34. }
  35. else {
  36. this.head = next;
  37. }
  38. if (next) {
  39. next.prev = prev;
  40. }
  41. else {
  42. this.tail = prev;
  43. }
  44. entry.next = entry.prev = null;
  45. this._len--;
  46. };
  47. LinkedList.prototype.len = function () {
  48. return this._len;
  49. };
  50. LinkedList.prototype.clear = function () {
  51. this.head = this.tail = null;
  52. this._len = 0;
  53. };
  54. return LinkedList;
  55. }());
  56. export { LinkedList };
  57. var LRU = (function () {
  58. function LRU(maxSize) {
  59. this._list = new LinkedList();
  60. this._maxSize = 10;
  61. this._map = {};
  62. this._maxSize = maxSize;
  63. }
  64. LRU.prototype.put = function (key, value) {
  65. var list = this._list;
  66. var map = this._map;
  67. var removed = null;
  68. if (map[key] == null) {
  69. var len = list.len();
  70. var entry = this._lastRemovedEntry;
  71. if (len >= this._maxSize && len > 0) {
  72. var leastUsedEntry = list.head;
  73. list.remove(leastUsedEntry);
  74. delete map[leastUsedEntry.key];
  75. removed = leastUsedEntry.value;
  76. this._lastRemovedEntry = leastUsedEntry;
  77. }
  78. if (entry) {
  79. entry.value = value;
  80. }
  81. else {
  82. entry = new Entry(value);
  83. }
  84. entry.key = key;
  85. list.insertEntry(entry);
  86. map[key] = entry;
  87. }
  88. return removed;
  89. };
  90. LRU.prototype.get = function (key) {
  91. var entry = this._map[key];
  92. var list = this._list;
  93. if (entry != null) {
  94. if (entry !== list.tail) {
  95. list.remove(entry);
  96. list.insertEntry(entry);
  97. }
  98. return entry.value;
  99. }
  100. };
  101. LRU.prototype.clear = function () {
  102. this._list.clear();
  103. this._map = {};
  104. };
  105. LRU.prototype.len = function () {
  106. return this._list.len();
  107. };
  108. return LRU;
  109. }());
  110. export default LRU;