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.

JavascriptData Fetching

Code

javascriptsnippet
24 lines
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 <= 0 short-circuits the flow with an early throw when 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

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.