class LRUCache { #map; #length; constructor(len) { this.#length = len; this.#map = new Map(); } has(key) { return this.#map.has(key); } get(key) { if (!this.has(key)) return null; let value = this.#map.get(key); this.#map.delete(key); this.#map.set(key, value); return value; } set(key, value) { if (this.#map.size >= this.#length) { this.#map.delete(this.#map.keys().next().value); } if (this.has(key)) { this.#map.delete(key); } this.#map.set(key, value); } }
let cache = new LRUCache(3); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); console.log(cache);
cache.get("a");
console.log(cache); cache.set("d", 4);
console.log(cache);
|