cache.js 1.3 KB

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