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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.
