lrucache.js 788 B

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