LRU Cache Implementation in JavaScript
Level 5546 keystrokes
LRU Cache evicts the least recently used item when capacity is exceeded.
JavaScript code
// LRU (Least Recently Used) Cache using Map1class LRUCache {2 constructor(capacity) { // Set maximum number of items3 this.capacity = capacity; // Map maintains insertion order4 this.cache = new Map();5 }6 get(key) { // Return -1 if key doesn't exist7 if (!this.cache.has(key)) return -1; // Get the value8 const val = this.cache.get(key); // Move to end (most recently used) by re-inserting9 this.cache.delete(key);10 this.cache.set(key, val);11 return val;12 }13 put(key, value) { // Delete if exists (to update position)14 this.cache.delete(key); // Add to end (most recently used)15 this.cache.set(key, value); // If over capacity, remove oldest (first) item16 if (this.cache.size > this.capacity) { // keys().next().value is the first (oldest) key17 this.cache.delete(this.cache.keys().next().value);18 }19 }20}21 // Create cache with capacity 222const cache = new LRUCache(2);// Add items23cache.put(1, "a"); cache.put(2, "b");// Get 1 (makes it most recently used)24console.log(cache.get(1));// Add 3, evicts 2 (least recently used)25cache.put(3, "c");// 2 was evicted, returns -126console.log(cache.get(2));Output
a -1
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
.× 30(× 23)× 23;× 16,× 6"× 6{× 5}× 5=× 4-× 1