You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.1 KiB

  1. /*!
  2. * Connect - Cache
  3. * Copyright(c) 2011 Sencha Inc.
  4. * MIT Licensed
  5. */
  6. /**
  7. * Expose `Cache`.
  8. */
  9. module.exports = Cache;
  10. /**
  11. * LRU cache store.
  12. *
  13. * @param {Number} limit
  14. * @api private
  15. */
  16. function Cache(limit) {
  17. this.store = {};
  18. this.keys = [];
  19. this.limit = limit;
  20. }
  21. /**
  22. * Touch `key`, promoting the object.
  23. *
  24. * @param {String} key
  25. * @param {Number} i
  26. * @api private
  27. */
  28. Cache.prototype.touch = function(key, i){
  29. this.keys.splice(i,1);
  30. this.keys.push(key);
  31. };
  32. /**
  33. * Remove `key`.
  34. *
  35. * @param {String} key
  36. * @api private
  37. */
  38. Cache.prototype.remove = function(key){
  39. delete this.store[key];
  40. };
  41. /**
  42. * Get the object stored for `key`.
  43. *
  44. * @param {String} key
  45. * @return {Array}
  46. * @api private
  47. */
  48. Cache.prototype.get = function(key){
  49. return this.store[key];
  50. };
  51. /**
  52. * Add a cache `key`.
  53. *
  54. * @param {String} key
  55. * @return {Array}
  56. * @api private
  57. */
  58. Cache.prototype.add = function(key){
  59. // initialize store
  60. var len = this.keys.push(key);
  61. // limit reached, invalidate LRU
  62. if (len > this.limit) this.remove(this.keys.shift());
  63. var arr = this.store[key] = [];
  64. arr.createdAt = new Date;
  65. return arr;
  66. };