liveBook · Manning

LRU

As explained in Acing the Frontend Interview

Least recently used eviction removes the cache item with the oldest recorded access when space is needed.

LRU (Least Recently Used) eviction removes the item whose recorded access is oldest when a cache exceeds its capacity. It keeps frequently accessed data available and is commonly applied in memory-bound systems. section 6.4

An interview-ready implementation combines:

  • A hash map for constant-time key lookup. section 6.4
  • A Map whose insertion order records recency; every access or insertion moves the key to the end. section 6.4
  • Eviction of the first Map key when capacity is exceeded. section 6.4

TypeScript cache

A generic LRUCache validates positive capacity, implements get and put, refreshes recency by deleting and reinserting accessed keys, and returns -1 for misses. section 6.4

Listing 6.6 LRU cache implementation in TypeScript
class LRUCache<K, V> {
  private cache: Map<K, V>;
  private capacity: number;
   constructor(capacity: number) {
    if (capacity <= 0) {
      throw new Error('Capacity must be greater than 0');
    }
    this.capacity = capacity; #A
    this.cache = new Map(); #B
  }
  get(key: K): V | -1 { #C
    if (!this.cache.has(key)) { #D
      return -1;
    }
    const value = this.cache.get(key)!; #E
    this.cache.delete(key);
    this.cache.set(key, value);
    return value;
  }
  put(key: K, value: V): void { #F
    if (this.cache.has(key)) {
      this.cache.delete(key); #G
    }
    this.cache.set(key, value); #H
    if (this.cache.size > this.capacity) {
      const lruKey = this.cache.keys().next().value!; #I
      this.cache.delete(lruKey); #J
    }
  }
  entries(): [K, V][] { #K
    return Array.from(this.cache.entries());
  }
}

Inspect the complete TypeScript implementation, including capacity validation, lookup, recency updates, insertion, eviction, and entry inspection. section 6.4

How Acing the Frontend Interview covers it

How deep it goes
Explains eviction behavior, recency tracking, constant-time operations, and a complete TypeScript implementation.
Examples
Uses a TypeScript LRUCache, a React demo, and stale-entry eviction such as 1 → 1.
What it assumes
Assumes familiarity with caching algorithms and data structures while defining LRU eviction behavior.
What you can do after
Build it from scratch with TypeScript Map operations that provide constant-time access, insertion, recency updates, and eviction.
How it connects
Connects LRU with caching strategies, hash maps, JavaScript Map ordering, multi-tier caching, and React integration.

Also explained in

Compare how 5 books explain LRU →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Acing the Frontend Interview. The section links point to the parts of the book it draws on.