lrucache.js 802 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict'
  2. class LRUCache {
  3. constructor () {
  4. this.max = 1000
  5. this.map = new Map()
  6. }
  7. get (key) {
  8. const value = this.map.get(key)
  9. if (value === undefined) {
  10. return undefined
  11. } else {
  12. // Remove the key from the map and add it to the end
  13. this.map.delete(key)
  14. this.map.set(key, value)
  15. return value
  16. }
  17. }
  18. delete (key) {
  19. return this.map.delete(key)
  20. }
  21. set (key, value) {
  22. const deleted = this.delete(key)
  23. if (!deleted && value !== undefined) {
  24. // If cache is full, delete the least recently used item
  25. if (this.map.size >= this.max) {
  26. const firstKey = this.map.keys().next().value
  27. this.delete(firstKey)
  28. }
  29. this.map.set(key, value)
  30. }
  31. return this
  32. }
  33. }
  34. module.exports = LRUCache