From 3f5f27335282cf811dcfa85bc8a2bc0ef5fb2493 Mon Sep 17 00:00:00 2001 From: xo-clds Date: Sat, 17 Jan 2026 20:02:23 +0530 Subject: [PATCH 1/2] Create lru.js --- Algorithms/Javascript/lru.js | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Algorithms/Javascript/lru.js diff --git a/Algorithms/Javascript/lru.js b/Algorithms/Javascript/lru.js new file mode 100644 index 0000000..2538389 --- /dev/null +++ b/Algorithms/Javascript/lru.js @@ -0,0 +1,48 @@ +class LRUCache { + constructor(capacity) { + this.capacity = capacity; + this.cache = new Map(); + } + + get(key) { + if (!this.cache.has(key)) return -1; + + const value = this.cache.get(key); + + this.cache.delete(key); + this.cache.set(key, value); + + return value; + } + + put(key, value) { + if (this.cache.has(key)) { + this.cache.delete(key); + } + + this.cache.set(key, value); + + if (this.cache.size > this.capacity) { + const lruKey = this.cache.keys().next().value; + this.cache.delete(lruKey); + } + } + + display() { + const arr = []; + for (const [key, value] of this.cache.entries()) { + arr.push(`[key=${key} value=${value}]`); + } + console.log(`[${arr.join(", ")}]`); + } +} + +const cache = new LRUCache(5); + +for (let i = 1; i <= 5; i++) { + cache.put(i, i * 2 + 3); +} + +cache.display(); + +console.log("Getting key 3:", cache.get(3)); From ef0ab43ce15c2205a90c31559b3c8fd2e5660b36 Mon Sep 17 00:00:00 2001 From: Ritik Ranjan Date: Sat, 17 Jan 2026 20:04:53 +0530 Subject: [PATCH 2/2] Fix string quotes in lru.js Make eslint happy --- Algorithms/Javascript/lru.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Algorithms/Javascript/lru.js b/Algorithms/Javascript/lru.js index 2538389..35a91d0 100644 --- a/Algorithms/Javascript/lru.js +++ b/Algorithms/Javascript/lru.js @@ -33,16 +33,16 @@ class LRUCache { for (const [key, value] of this.cache.entries()) { arr.push(`[key=${key} value=${value}]`); } - console.log(`[${arr.join(", ")}]`); + console.log(`[${arr.join(', ')}]`); } } const cache = new LRUCache(5); for (let i = 1; i <= 5; i++) { - cache.put(i, i * 2 + 3); + cache.put(i, i * 2 + 3); } cache.display(); -console.log("Getting key 3:", cache.get(3)); +console.log('Getting key 3:', cache.get(3));