lru.js 1.5 KB

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