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 Map
1class LRUCache {
2 constructor(capacity) {
// Set maximum number of items
3 this.capacity = capacity;
// Map maintains insertion order
4 this.cache = new Map();
5 }
6 get(key) {
// Return -1 if key doesn't exist
7 if (!this.cache.has(key)) return -1;
// Get the value
8 const val = this.cache.get(key);
// Move to end (most recently used) by re-inserting
9 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) item
16 if (this.cache.size > this.capacity) {
// keys().next().value is the first (oldest) key
17 this.cache.delete(this.cache.keys().next().value);
18 }
19 }
20}
21
// Create cache with capacity 2
22const cache = new LRUCache(2);
// Add items
23cache.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 -1
26console.log(cache.get(2));

Output

a
-1
Practice typing this code

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

More JavaScript examples at level 5

← JavaScript typing practice