cache.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2016 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. "use strict"
  7. //------------------------------------------------------------------------------
  8. // Helpers
  9. //------------------------------------------------------------------------------
  10. const SKIP_TIME = 5000
  11. //------------------------------------------------------------------------------
  12. // Public Interface
  13. //------------------------------------------------------------------------------
  14. /**
  15. * The class of cache.
  16. * The cache will dispose of each value if the value has not been accessed
  17. * during 5 seconds.
  18. */
  19. module.exports = class Cache {
  20. /**
  21. * Initialize this cache instance.
  22. */
  23. constructor() {
  24. this.map = new Map()
  25. }
  26. /**
  27. * Get the cached value of the given key.
  28. * @param {any} key The key to get.
  29. * @returns {any} The cached value or null.
  30. */
  31. get(key) {
  32. const entry = this.map.get(key)
  33. const now = Date.now()
  34. if (entry) {
  35. if (entry.expire > now) {
  36. entry.expire = now + SKIP_TIME
  37. return entry.value
  38. }
  39. this.map.delete(key)
  40. }
  41. return null
  42. }
  43. /**
  44. * Set the value of the given key.
  45. * @param {any} key The key to set.
  46. * @param {any} value The value to set.
  47. * @returns {void}
  48. */
  49. set(key, value) {
  50. const entry = this.map.get(key)
  51. const expire = Date.now() + SKIP_TIME
  52. if (entry) {
  53. entry.value = value
  54. entry.expire = expire
  55. }
  56. else {
  57. this.map.set(key, { value, expire })
  58. }
  59. }
  60. }