Created
May 24, 2020 02:30
-
-
Save boizz/3748f8189dc3e112259f41f2219ea34b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class ListNode { | |
constructor({ | |
prev, | |
next, | |
val, | |
hNext, | |
}) { | |
this.prev = prev; | |
this.next = next; | |
this.val = val; | |
this.hNext = hNext; | |
} | |
} | |
export class LRUCache { | |
constructor(capacity) { | |
this.capacity = capacity; | |
this.hash = null; | |
this.head = null; | |
} | |
get = (key) => { | |
if (this.hash) { | |
const node = this.hash.get(key); | |
if (node) { | |
if (node === this.tail) { | |
if (!this.tail.prev) { | |
return node.val; | |
} | |
this.tail = this.tail.prev; | |
this.tail.next = null; | |
} | |
if (node.prev) { | |
node.prev.next = node.next; | |
} | |
if (node.next) { | |
node.next.prev = node.prev; | |
} | |
this.head.prev = node; | |
node.next = this.head; | |
node.prev = null; | |
this.head = node; | |
return node.val; | |
} | |
} | |
return -1; | |
} | |
put = (key, data) => { | |
const node = new ListNode({ | |
prev: null, | |
val: data, | |
next: null, | |
hNext: key, | |
}); | |
if (this.hash && this.tail && this.head) { | |
if (this.hash.get(key)) { | |
this.get(key); | |
} else { | |
if (this.hash.size >= this.capacity) { | |
this.hash.delete(this.tail.hNext); | |
this.tail = this.tail.prev; | |
if (this.tail) { | |
this.tail.next = null; | |
} | |
} | |
this.head.prev = node; | |
node.next = this.head; | |
this.head = node; | |
} | |
} else { | |
this.hash = new Map(); | |
this.head = node; | |
this.tail = node; | |
} | |
this.hash.set(key, node); | |
} | |
} | |
export default LRUCache; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment