LRU Cache With Map Ordering
Implement a least-recently-used cache that evicts the oldest entry when capacity is exceeded, reusing Map insertion order to track recency.
Code
export class LruCache {
constructor(capacity) {
if (capacity <= 0) throw new RangeError("capacity must be positive");
this.capacity = capacity;
this.entries = new Map();
}
get(key) {
if (!this.entries.has(key)) return undefined;
const value = this.entries.get(key);
this.entries.delete(key);
this.entries.set(key, value);
return value;
}
set(key, value) {
if (this.entries.has(key)) this.entries.delete(key);
this.entries.set(key, value);
if (this.entries.size > this.capacity) {
const oldest = this.entries.keys().next().value;
this.entries.delete(oldest);
}
}
}How the snippet works
The working surface is the class LruCache — everything else is wiring.
Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.
Points of care
- The guard
capacity <= 0short-circuits the flow with an earlythrowwhen its condition holds.
Using it
LruCache is the public entry point; everything else in the file exists to support it.
Key statements
if (capacity <= 0) throw new RangeError("capacity must be positive");
if (!this.entries.has(key)) return undefined;
this.entries = new Map();
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- What happens if the preconditions do not hold?
- Validation comes first — `RangeError` marks the failure at `capacity <= 0`, before any partial work happens.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced.
Report a problem with this exampleOpens a pre-filled issue on GitHub.