LRU (Least Recently Used) Cache
class LRUCache {
constructor(n) {
this.maxLength = n;
this.cache = new Map();
}
put(key, value) {
if (this.cache.size >= this.maxLength) {
// Remove LRU Item
let firstItem = this.cache.keys().next().value;
this.cache.delete(firstItem);
}
this.cache.set(key, value);
this.updateRecentness(key);
this.printCache();
}
get(key) {
if (this.cache.has(key)) {
this.updateRecentness(key);
this.printCache();
return this.cache.get(key);
}
console.log(-1);
return -1;
}
printCache() {
console.log(this.cache);
}
updateRecentness(key) {
let value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
}
}
const cache = new LRUCache(3);
cache.put("x", 5);
cache.put("y", 7);
cache.put("z", 8);
cache.get("x");
cache.put("a", 9);
cache.get("y");
cache.put("b", 4);
// x
// y x
// z y x
// x z y
// a x z
// -1
// b a x
// Consider the Map as a stack, So order is from back.
// Map(1) { 'x' => 5 }
// Map(2) { 'x' => 5, 'y' => 7 }
// Map(3) { 'x' => 5, 'y' => 7, 'z' => 8 }
// Map(3) { 'y' => 7, 'z' => 8, 'x' => 5 }
// Map(3) { 'z' => 8, 'x' => 5, 'a' => 9 }
// -1
// Map(3) { 'x' => 5, 'a' => 9, 'b' => 4 }