QuickLru.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var isUndef = require('./isUndef');
  2. var Class = require('./Class');
  3. exports = Class({
  4. initialize: function QuickLru(max) {
  5. this._max = max;
  6. this._cache = {};
  7. this._oldCache = {};
  8. this._size = 0;
  9. },
  10. has: function(key) {
  11. return !isUndef(this._cache[key]) || !isUndef(this._oldCache[key]);
  12. },
  13. remove: function(key) {
  14. if (!isUndef(this._cache[key])) this._cache[key] = undefined;
  15. if (!isUndef(this._oldCache[key])) this._oldCache[key] = undefined;
  16. },
  17. get: function(key) {
  18. if (!isUndef(this._cache[key])) {
  19. return this._cache[key];
  20. }
  21. var val = this._oldCache[key];
  22. if (!isUndef(val)) {
  23. this._update(key, val);
  24. return val;
  25. }
  26. },
  27. set: function(key, val) {
  28. if (!isUndef(this._cache[key])) {
  29. this._cache[key] = val;
  30. } else {
  31. this._update(key, val);
  32. }
  33. },
  34. clear: function() {
  35. this._cache = {};
  36. this._oldCache = {};
  37. },
  38. _update: function(key, val) {
  39. this._cache[key] = val;
  40. this._size++;
  41. if (this._size > this._max) {
  42. this._size = 0;
  43. this._oldCache = this._cache;
  44. this._cache = {};
  45. }
  46. }
  47. });
  48. module.exports = exports;