LRU Cache
Javascript
Data Structures
Web Development
Programming

LRU cache implementation in Javascript

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

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

  1. 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).
  2. 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.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.