LRU cache implementation in Javascript
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In the world of computer science, efficient data retrieval and storage are crucial for performance. Among various caching strategies, the Least Recently Used (LRU) cache is a popular choice. An LRU cache removes the least recently used items to make space for new data.
This article explains how to implement an LRU cache in JavaScript, offering insights into its operations and providing context with examples.
How LRU Cache Works
An LRU cache keeps track of the order in which items are accessed, ensuring that the least recently accessed data is the first to be removed when the cache reaches its capacity. To achieve an efficient LRU mechanism, the cache typically uses a combination of a doubly-linked list and a hash map (object in JavaScript).
Key Components
- Doubly-Linked List:
- Keeps track of the usage order.
- Fast insertion and deletion operations.
- Constant time access to head (most recently used) and tail (least recently used).
- Hash Map:
- Provides constant time access to cache items.
- Maps keys to nodes in the doubly-linked list.
Implementation in JavaScript
Setting Up the LRU Cache
- Represents each cache entry with properties `key`, `value`, `prev`, and `next`.
- Initializes with a specified `capacity`.
- Uses a `Map` to store key-node pairs and a doubly-linked list to manage order.
- `_remove(node)` removes a node from the list.
- `_add(node)` adds a node to the end of the list (most recently used).
- `get(key)`: Retrieves the value from the cache for the given key if present, updating its position (recently used). Returns `-1` on a cache miss.
- `put(key, value)`: Adds a new key-value pair or updates an existing one, ensuring the order is maintained. If the cache is full, it removes the least recently used item.
- The implementation is not thread-safe. In a multi-threaded environment, consider applying locks or using atomic operations for safety.
- Allow capacity adjustment post initialization to make the cache adapt to varying workloads.
- Consider integrating file or database I/O for persistent caching across application restarts.
- Add expiry times for cache entries to automatically remove stale data.

