Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Node {
  2.   constructor(key, data) {
  3.     this.key = key
  4.     this.data = data
  5.     this.prev = null
  6.     this.next = null
  7.   }
  8. }
  9.  
  10. class LinkedList {
  11.   constructor() {
  12.     this.head = null
  13.     this.tail = null
  14.   }
  15.  
  16.   append(key, data) {
  17.     let node = new Node(key, data)
  18.    
  19.     if (this.head === null) {
  20.       this.head = node
  21.       this.tail = node
  22.     } else {
  23.       node.prev = this.tail
  24.       this.tail.next = node
  25.       this.tail = node
  26.     }
  27.    
  28.     return node
  29.   }
  30.  
  31.   remove(node) {
  32.     let prev = node.prev
  33.     let next = node.next
  34.     if (prev) {
  35.       node.prev.next = node.next
  36.     } else {
  37.       this.head = node.next
  38.     }
  39.     if (next) {
  40.       node.next.prev = node.prev
  41.     } else {
  42.       this.tail = node.prev
  43.     }
  44.   }
  45. }
  46.  
  47. class Cache {
  48.   constructor(size) {
  49.     this.size = size
  50.     this.map = new Map()
  51.     this.list = new LinkedList()
  52.   }
  53.  
  54.   add(key, data) {
  55.     if (this.map.has(key)) {
  56.       const oldNode = this.map.get(key)
  57.       this.list.remove(oldNode)
  58.     } else {
  59.       if (this.map.size === this.size) {
  60.         this.map.delete(this.list.head.key)
  61.         this.list.remove(this.list.head)
  62.       }
  63.     }
  64.    
  65.     const node = this.list.append(key, data)
  66.     this.map.set(key, node)
  67.   }
  68.  
  69.   get(key) {
  70.     if (!this.map.has(key)) {
  71.       return undefined
  72.     }
  73.     return this.map.get(key).data
  74.   }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement