class LRUCache {
#map;
#length;
constructor(len) {
this.#map = new Map();
this.#length = len;
}
has(key) {
return this.#map.has(key);
}
get(key) {
if (!this.has(key)) return null;
const value = this.#map.get(key);
this.#map.delete(key);
this.#map.set(key, value);
return value;
}
set(key, value) {
if (this.has(key)) {
this.#map.delete(key);
}
this.#map.set(key, value);
if (this.#map.size > this.#length) {
this.#map.delete(this.#map.keys().next().value);
}
}
}
const cache = new LRUCache(3);
cache.set("one", 1);
cache.set("two", 2);
cache.set("three", 3);
cache.set("four", 4);
console.log(cache.get("one"));
console.log(cache.get("two"));
console.log(cache.get("three"));
console.log(cache.get("four"));
cache.set("five", 5);
console.log(cache.get("two"));