snippetjavascriptModeratepending
LRU Cache implementation in JavaScript
Viewed 0 times
LRU cacheleast recently usedMapmemoizationcache evictionbounded cache
browsernodejs
Problem
Need a fixed-size cache that evicts the least recently used entries when full. Useful for memoization, API response caching, and avoiding repeated expensive computations.
Solution
LRU Cache using Map which preserves insertion order. O(1) get and set operations. Evicts oldest entry when capacity is exceeded.
Code Snippets
LRU Cache with Map for O(1) operations
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return undefined;
const value = this.cache.get(key);
// Move to end (most recent)
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
set(key, value) {
if (this.cache.has(key)) this.cache.delete(key);
this.cache.set(key, value);
if (this.cache.size > this.capacity) {
// Delete oldest (first key)
const oldest = this.cache.keys().next().value;
this.cache.delete(oldest);
}
}
has(key) { return this.cache.has(key); }
get size() { return this.cache.size; }
clear() { this.cache.clear(); }
}
// Usage
const cache = new LRUCache(100);
cache.set('user:1', { name: 'Alice' });
cache.get('user:1'); // { name: 'Alice' }Revisions (0)
No revisions yet.