Created
August 7, 2022 21:31
-
-
Save alex700/b286d65dca58427530ea5582d6944b9d to your computer and use it in GitHub Desktop.
LRU Cache Implementation
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
class LruCache { | |
constructor(capacity) { | |
this.capacity = capacity; | |
this.map = new Map(); | |
} | |
get(key) { | |
if(this.map.has(key)) { | |
let val = this.map.get(key); | |
this.map.delete(key); | |
this.map.set(key, val) | |
return val; | |
} | |
return -1 | |
} | |
put(key, val) { | |
if(this.get(key) === -1) { | |
if(this.capacity === this.map.size && this.map.size > 0) { | |
const keys = this.map.keys(); | |
this.map.delete(keys.next().value); | |
} | |
} | |
this.map.set(key, val); | |
} | |
} | |
const lc = new LruCache(2); | |
lc.put(1, 1) // [1 => 1] | |
lc.put(2, 2) // [1 => 1, 2 => 2] | |
console.assert(lc.get(1), 1); // [2 => 2, 1 => 1] | |
lc.put(3, 3) // [1 => 1, 3 => 3] | |
console.assert(lc.get(2), -1) // [1 => 1, 3 => 3] | |
lc.put(4, 4) // [3 => 3, 4 => 4] | |
console.assert(lc.get(1), -1) // [3 => 3, 4 => 4] | |
console.assert(lc.get(3), 3) // [4 => 4, 3 => 3] | |
console.assert(lc.get(4), 4) // [3 => 3, 4 => 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment