memory-cache.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. function MemoryCache() {
  2. this.cache = {}
  3. this.size = 0
  4. }
  5. MemoryCache.prototype.add = function (key, value, time, timeoutCallback) {
  6. var old = this.cache[key]
  7. var instance = this
  8. var entry = {
  9. value: value,
  10. expire: time + Date.now(),
  11. timeout: setTimeout(function () {
  12. instance.delete(key)
  13. return (
  14. timeoutCallback &&
  15. typeof timeoutCallback === 'function' &&
  16. timeoutCallback(value, key)
  17. )
  18. }, time),
  19. }
  20. this.cache[key] = entry
  21. this.size = Object.keys(this.cache).length
  22. return entry
  23. }
  24. MemoryCache.prototype.delete = function (key) {
  25. var entry = this.cache[key]
  26. if (entry) {
  27. clearTimeout(entry.timeout)
  28. }
  29. delete this.cache[key]
  30. this.size = Object.keys(this.cache).length
  31. return null
  32. }
  33. MemoryCache.prototype.get = function (key) {
  34. var entry = this.cache[key]
  35. return entry
  36. }
  37. MemoryCache.prototype.getValue = function (key) {
  38. var entry = this.get(key)
  39. return entry && entry.value
  40. }
  41. MemoryCache.prototype.clear = function () {
  42. Object.keys(this.cache).forEach(function (key) {
  43. this.delete(key)
  44. }, this)
  45. return true
  46. }
  47. module.exports = MemoryCache