lru.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. /** A simple Least Recently Used map */
  3. class LRUMap {
  4. constructor( _maxSize) {this._maxSize = _maxSize;
  5. this._cache = new Map();
  6. }
  7. /** Get the current size of the cache */
  8. get size() {
  9. return this._cache.size;
  10. }
  11. /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
  12. get(key) {
  13. const value = this._cache.get(key);
  14. if (value === undefined) {
  15. return undefined;
  16. }
  17. // Remove and re-insert to update the order
  18. this._cache.delete(key);
  19. this._cache.set(key, value);
  20. return value;
  21. }
  22. /** Insert an entry and evict an older entry if we've reached maxSize */
  23. set(key, value) {
  24. if (this._cache.size >= this._maxSize) {
  25. // keys() returns an iterator in insertion order so keys().next() gives us the oldest key
  26. this._cache.delete(this._cache.keys().next().value);
  27. }
  28. this._cache.set(key, value);
  29. }
  30. /** Remove an entry and return the entry if it was in the cache */
  31. remove(key) {
  32. const value = this._cache.get(key);
  33. if (value) {
  34. this._cache.delete(key);
  35. }
  36. return value;
  37. }
  38. /** Clear all entries */
  39. clear() {
  40. this._cache.clear();
  41. }
  42. /** Get all the keys */
  43. keys() {
  44. return Array.from(this._cache.keys());
  45. }
  46. /** Get all the values */
  47. values() {
  48. const values = [];
  49. this._cache.forEach(value => values.push(value));
  50. return values;
  51. }
  52. }
  53. exports.LRUMap = LRUMap;
  54. //# sourceMappingURL=lru.js.map