LRU (Least Recently Used) Cache is a type of cache that evicts the least recently accessed item when the cache exceeds its capacity. It's useful in scenarios where memory is limited, and you want to cache only the most frequently accessed data.
In JavaScript, an LRU Cache can be implemented using a combination of a Map (for fast lookups and maintaining insertion order) and a Doubly Linked List (for efficient insertions and deletions at both ends). However, for simplicity, we'll use a Map in the following implementation.
Here’s a JavaScript implementation of an LRU Cache:
class LRUCache { constructor(capacity) { this.capacity = capacity; this.cache = new Map(); // Using Map to maintain key-value pairs } // Get the value from the cache get(key) { if (!this.cache.has(key)) { return -1; // If the key is not found, return -1 } // Key is found, move the key to the most recent position const value = this.cache.get(key); this.cache.delete(key); // Remove the old entry this.cache.set(key, value); // Reinsert to update its position (most recently used) return value; } // Add or update the value in the cache put(key, value) { if (this.cache.has(key)) { // If the key already exists, remove it to update its position this.cache.delete(key); } else if (this.cache.size >= this.capacity) { // If the cache is at capacity, delete the least recently used item const leastRecentlyUsedKey = this.cache.keys().next().value; this.cache.delete(leastRecentlyUsedKey); } // Insert the new key-value pair (most recent) this.cache.set(key, value); } }
Explanation:
Constructor: The LRUCache class is initialized with a given capacity, and it uses a Map to store the cached key-value pairs. The Map keeps track of the insertion order, which helps identify the least recently used (LRU) item.
get(key):
- If the key exists in the cache, the method returns its value and moves the key to the most recent position by first deleting the key and then reinserting it.
- If the key doesn't exist, it returns -1.
put(key, value):
- If the key already exists in the cache, it removes the key and reinserts it (updating its position as the most recently used).
- If the cache reaches its capacity, it removes the least recently used key (the first one in the Map).
- Finally, the new key-value pair is added to the cache.
Usage Example:
const lruCache = new LRUCache(3); // Cache with a capacity of 3 lruCache.put(1, 'one'); // Add key 1 lruCache.put(2, 'two'); // Add key 2 lruCache.put(3, 'three'); // Add key 3 console.log(lruCache.get(1)); // Output: 'one' (key 1 becomes the most recently used) lruCache.put(4, 'four'); // Cache is full, so it evicts key 2 (least recently used) console.log(lruCache.get(2)); // Output: -1 (key 2 has been evicted) console.log(lruCache.get(3)); // Output: 'three' (key 3 is still in the cache) console.log(lruCache.get(4)); // Output: 'four' (key 4 is in the cache)
The above is the detailed content of LRU (Least Recently Used) Cache Data Structure. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools