LRU Cache using JavaScript Last Updated : 28 Jun, 2024 Comments Improve Suggest changes Like Article Like Report The LRU (Least Recently Used) Cache is a type of the data structure that is used to the store a limited number of items with the capability to the quickly retrieve and manage these items. When the cache reaches its limit the least recently used item is removed to the make space for the new item. This is particularly useful in the scenarios where you need to the maintain a fixed amount of the data and ensure quick access and updates such as in web browsers database management systems and memory management.These are the following approaches:Table of ContentUsing Map and Doubly Linked ListUsing Map and ArrayUsing Map and Doubly Linked ListThe combination of a Map and a Doubly Linked List is a common approach to the implement an LRU Cache. The Map provides an average O(1) time complexity for the get and set operations while the Doubly Linked List helps in the keeping track of the order of the usage. When an item is accessed it is moved to the front of list ensuring that the least recently used item is at the end of the list.Example: This illustrates an LRUCache (Least Recently Used Cache) data structure in JavaScript using a doubly linked list and a map, allowing efficient storage and retrieval of key-value pairs with a specified capacity, discarding the least recently used items when the capacity is exceeded. JavaScript class ListNode { constructor(key, value) { this.key = key; this.value = value; this.prev = null; this.next = null; } } class LRUCache { constructor(capacity) { this.capacity = capacity; this.cache = new Map(); this.head = new ListNode(null, null); this.tail = new ListNode(null, null); this.head.next = this.tail; this.tail.prev = this.head; } _remove(node) { let prev = node.prev; let next = node.next; prev.next = next; next.prev = prev; } _add(node) { let next = this.head.next; this.head.next = node; node.prev = this.head; node.next = next; next.prev = node; } get(key) { if (!this.cache.has(key)) { return -1; } let node = this.cache.get(key); this._remove(node); this._add(node); return node.value; } put(key, value) { if (this.cache.has(key)) { this._remove(this.cache.get(key)); } let newNode = new ListNode(key, value); this._add(newNode); this.cache.set(key, newNode); if (this.cache.size > this.capacity) { let lru = this.tail.prev; this._remove(lru); this.cache.delete(lru.key); } } } // Example usage let lru = new LRUCache(2); lru.put(1, 1); lru.put(2, 2); console.log(lru.get(1)); lru.put(3, 3); console.log(lru.get(2)); lru.put(4, 4); console.log(lru.get(1)); console.log(lru.get(3)); console.log(lru.get(4)); Output1 -1 -1 3 4 Time Complexity: O(1) for the both get and put operations.Using Map and ArrayThis approach is to the use a Map in conjunction with the Array. The Map provides the fast access to the cache items while the Array keeps track of the order in which items were used. This method is simpler but less efficient for the large caches due to the need to perform the array operations to the maintain the order.Example: This illustrates an LRU (Least Recently Used) cache using a Map and an array to store key-value pairs with a fixed capacity. JavaScript class LRUCache { constructor(capacity) { this.capacity = capacity; this.cache = new Map(); this.order = []; } get(key) { if (!this.cache.has(key)) { return -1; } let value = this.cache.get(key); this._updateOrder(key); return value; } put(key, value) { if (this.cache.has(key)) { this.cache.set(key, value); this._updateOrder(key); } else { if (this.cache.size >= this.capacity) { let lru = this.order.shift(); this.cache.delete(lru); } this.cache.set(key, value); this.order.push(key); } } _updateOrder(key) { let index = this.order.indexOf(key); if (index > -1) { this.order.splice(index, 1); } this.order.push(key); } } // Example usage let lru = new LRUCache(2); lru.put(1, 1); lru.put(2, 2); console.log(lru.get(1)); lru.put(3, 3); console.log(lru.get(2)); lru.put(4, 4); console.log(lru.get(1)); console.log(lru.get(3)); console.log(lru.get(4)); Output1 -1 -1 3 4 Time complexity: O(n) for the updating the order array. Comment More infoAdvertise with us Next Article LRU Cache using JavaScript M maha123 Follow Improve Article Tags : JavaScript Web Technologies Similar Reads How to clear cache memory using JavaScript? Clearing cache memory in JavaScript refers to managing or removing stored data like images, files, and resources that browsers save for faster loading. Although JavaScript cannot directly clear the browser cache, developers often use cache-busting techniques to ensure users receive updated content.B 2 min read Pig Game Design using JavaScript In this article, we will be explaining the steps and various logic required in making of the famous Pig Game, which is a virtual dice game. About Game: In this game, User Interface (UI) contains user/player that can do three things, they are as follows:There will be two players in this game. At the 11 min read Create a Quiz Application Using JavaScript In this article, we will learn how to create a quiz application using JavaScript. The quiz application will contain questions followed by a total score shown at the end of the quiz. The score will increase based on the correct answers given. Initially, there are only three questions, but you can inc 4 min read How to Clear all Cookies using JavaScript? Cookies allow clients and servers to exchange information via HTTP, enabling state management despite HTTP being a stateless protocol. When a server sends a response, it can pass data to the user's browser in the form of key-value pairs, which the browser stores as cookies. On subsequent requests to 2 min read How JavaScript Works? JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f 13 min read Uses of JavaScript JavaScript is a versatile programming language extensively used in web development. It empowers interactive features like form validation, dynamic content updates, and user interface enhancements. Furthermore, it's employed in server-side scripting, mobile app development, game development, and even 3 min read How to Set & Retrieve Cookies using JavaScript ? In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user's browser. This cookie can be useful for storing user preferences, session information, and many more tasks. Table of Content Using document.cookieUsing js-cookie libraryUsing document 2 min read JavaScript sessionStorage JavaScript sessionStorage is a web storage technique that stores data for the duration of a page session. The sessionStorage object lets you store key/value pairs in the browser. It allows setting, retrieving, and managing data that persists only until the browser tab or window is closed, ensuring d 4 min read JavaScript Cookies JavaScript cookies are small data stored on a user's device by a web browser. These cookies play a crucial role in web development, enabling websites to store and retrieve information about user preferences, session states, and other data. Cookies facilitate a more personalized browsing experience b 3 min read HTML content modification using JavaScript JavaScript is the dynamic, lightweight, and most common computer programming language used to create web pages. It interacts with client-side and makes dynamic pages. JavaScript Can Change the Content of an HTML page. The getElementById() method is used to get the id of the element and change the HT 2 min read Like