{"id":13438164,"url":"https://github.com/rsms/js-lru","last_synced_at":"2025-05-13T16:12:07.825Z","repository":{"id":855362,"uuid":"587303","full_name":"rsms/js-lru","owner":"rsms","description":"A fast, simple \u0026 universal Least Recently Used (LRU) map for JavaScript","archived":false,"fork":false,"pushed_at":"2025-02-12T14:00:48.000Z","size":91,"stargazers_count":791,"open_issues_count":7,"forks_count":89,"subscribers_count":16,"default_branch":"master","last_synced_at":"2025-05-01T17:03:06.740Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rsms.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2010-03-30T20:32:37.000Z","updated_at":"2025-03-18T12:20:12.000Z","dependencies_parsed_at":"2025-02-20T13:15:31.836Z","dependency_job_id":"74c27281-4b19-45e1-94ae-74f445f24e98","html_url":"https://github.com/rsms/js-lru","commit_stats":{"total_commits":69,"total_committers":12,"mean_commits":5.75,"dds":0.5652173913043479,"last_synced_commit":"5373f60c42259bca06a99d2bb10d872ebe4ae72b"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsms%2Fjs-lru","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsms%2Fjs-lru/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsms%2Fjs-lru/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsms%2Fjs-lru/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rsms","download_url":"https://codeload.github.com/rsms/js-lru/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253171272,"owners_count":21865297,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T03:01:03.360Z","updated_at":"2025-05-13T16:12:02.816Z","avatar_url":"https://github.com/rsms.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# Least Recently Used (LRU) cache algorithm\n\nA finite key-value map using the [Least Recently Used (LRU)](http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used) algorithm, where the most recently-used items are \"kept alive\" while older, less-recently used items are evicted to make room for newer items.\n\nUseful when you want to limit use of memory to only hold commonly-used things.\n\n[![Test status](https://github.com/rsms/js-lru/workflows/npm-test/badge.svg)](https://github.com/rsms/js-lru/actions?query=workflow%3Anpm-test)\n\n\n## Terminology \u0026 design\n\n- Based on a doubly-linked list for low complexity random shuffling of entries.\n\n- The cache object iself has a \"head\" (least recently used entry) and a\n  \"tail\" (most recently used entry).\n\n- The \"oldest\" and \"newest\" are list entries -- an entry might have a \"newer\" and\n  an \"older\" entry (doubly-linked, \"older\" being close to \"head\" and \"newer\"\n  being closer to \"tail\").\n\n- Key lookup is done through a key-entry mapping native object, which on most\n  platforms mean `O(1)` complexity. This comes at a very low memory cost  (for\n  storing two extra pointers for each entry).\n\nFancy ASCII art illustration of the general design:\n\n```txt\n           entry             entry             entry             entry\n           ______            ______            ______            ______\n          | head |.newer =\u003e |      |.newer =\u003e |      |.newer =\u003e | tail |\n.oldest = |  A   |          |  B   |          |  C   |          |  D   | = .newest\n          |______| \u003c= older.|______| \u003c= older.|______| \u003c= older.|______|\n\n       removed  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  \u003c--  added\n```\n\n\n## Example\n\n```js\nlet c = new LRUMap(3)\nc.set('adam',   29)\nc.set('john',   26)\nc.set('angela', 24)\nc.toString()        // -\u003e \"adam:29 \u003c john:26 \u003c angela:24\"\nc.get('john')       // -\u003e 26\n\n// Now 'john' is the most recently used entry, since we just requested it\nc.toString()        // -\u003e \"adam:29 \u003c angela:24 \u003c john:26\"\nc.set('zorro', 141) // -\u003e {key:adam, value:29}\n\n// Because we only have room for 3 entries, adding 'zorro' caused 'adam'\n// to be removed in order to make room for the new entry\nc.toString()        // -\u003e \"angela:24 \u003c john:26 \u003c zorro:141\"\n```\n\n\n# Usage\n\n**Recommended:** Copy the code in lru.js or copy the lru.js and lru.d.ts files into your source directory. For minimal functionality, you only need the lines up until the comment that says \"Following code is optional\".\n\n**Using NPM:** [`yarn add lru_map`](https://www.npmjs.com/package/lru_map) (note that because NPM is one large flat namespace, you need to import the module as \"lru_map\" rather than simply \"lru\".)\n\n**Using AMD:** An [AMD](https://github.com/amdjs/amdjs-api/blob/master/AMD.md#amd) module loader like [`amdld`](https://github.com/rsms/js-amdld) can be used to load this module as well. There should be nothing to configure.\n\n**Testing**:\n\n- Run tests with `npm test`\n- Run benchmarks with `npm run benchmark`\n\n**Using with TypeScript**\n\nThis module comes with complete typing coverage for use with TypeScript. If you copied the code or files rather than using a module loader, make sure to include `lru.d.ts` into the same location where you put `lru.js`.\n\n```ts\nimport {LRUMap} from './lru'\n// import {LRUMap} from 'lru'     // when using via AMD\n// import {LRUMap} from 'lru_map' // when using from NPM\nconsole.log('LRUMap:', LRUMap)\n```\n\n\n# API\n\nThe API imitates that of [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), which means that in most cases you can use `LRUMap` as a drop-in replacement for `Map`.\n\n```ts\nexport class LRUMap\u003cK,V\u003e {\n  // Construct a new cache object which will hold up to limit entries.\n  // When the size == limit, a `put` operation will evict the oldest entry.\n  //\n  // If `entries` is provided, all entries are added to the new map.\n  // `entries` should be an Array or other iterable object whose elements are\n  // key-value pairs (2-element Arrays). Each key-value pair is added to the new Map.\n  // null is treated as undefined.\n  constructor(limit :number, entries? :Iterable\u003c[K,V]\u003e);\n\n  // Convenience constructor equivalent to `new LRUMap(count(entries), entries)`\n  constructor(entries :Iterable\u003c[K,V]\u003e);\n\n  // Current number of items\n  size :number;\n\n  // Maximum number of items this map can hold\n  limit :number;\n\n  // Least recently-used entry. Invalidated when map is modified.\n  oldest :Entry\u003cK,V\u003e;\n\n  // Most recently-used entry. Invalidated when map is modified.\n  newest :Entry\u003cK,V\u003e;\n\n  // Replace all values in this map with key-value pairs (2-element Arrays) from\n  // provided iterable.\n  assign(entries :Iterable\u003c[K,V]\u003e) : void;\n\n  // Put \u003cvalue\u003e into the cache associated with \u003ckey\u003e. Replaces any existing entry\n  // with the same key. Returns `this`.\n  set(key :K, value :V) : LRUMap\u003cK,V\u003e;\n\n  // Purge the least recently used (oldest) entry from the cache.\n  // Returns the removed entry or undefined if the cache was empty.\n  shift() : [K,V] | undefined;\n\n  // Get and register recent use of \u003ckey\u003e.\n  // Returns the value associated with \u003ckey\u003e or undefined if not in cache.\n  get(key :K) : V | undefined;\n\n  // Check if there's a value for key in the cache without registering recent use.\n  has(key :K) : boolean;\n\n  // Access value for \u003ckey\u003e without registering recent use. Useful if you do not\n  // want to chage the state of the map, but only \"peek\" at it.\n  // Returns the value associated with \u003ckey\u003e if found, or undefined if not found.\n  find(key :K) : V | undefined;\n\n  // Remove entry \u003ckey\u003e from cache and return its value.\n  // Returns the removed value, or undefined if not found.\n  delete(key :K) : V | undefined;\n\n  // Removes all entries\n  clear() : void;\n\n  // Returns an iterator over all keys, starting with the oldest.\n  keys() : Iterator\u003cK\u003e;\n\n  // Returns an iterator over all values, starting with the oldest.\n  values() : Iterator\u003cV\u003e;\n\n  // Returns an iterator over all entries, starting with the oldest.\n  entries() : Iterator\u003c[K,V]\u003e;\n\n  // Returns an iterator over all entries, starting with the oldest.\n  [Symbol.iterator]() : Iterator\u003c[K,V]\u003e;\n\n  // Call `fun` for each entry, starting with the oldest entry.\n  forEach(fun :(value :V, key :K, m :LRUMap\u003cK,V\u003e)=\u003evoid, thisArg? :any) : void;\n\n  // Returns an object suitable for JSON encoding\n  toJSON() : Array\u003c{key :K, value :V}\u003e;\n\n  // Returns a human-readable text representation\n  toString() : string;\n}\n\n// An entry holds the key and value, and pointers to any older and newer entries.\n// Entries might hold references to adjacent entries in the internal linked-list.\n// Therefore you should never store or modify Entry objects. Instead, reference the\n// key and value of an entry when needed.\ninterface Entry\u003cK,V\u003e {\n  key   :K;\n  value :V;\n}\n```\n\nIf you need to perform any form of finalization of items as they are evicted from the cache, wrapping the `shift` method is a good way to do it:\n\n```js\nlet c = new LRUMap(123);\nc.shift = function() {\n  let entry = LRUMap.prototype.shift.call(this);\n  doSomethingWith(entry);\n  return entry;\n}\n```\n\nThe internals calls `shift` as entries need to be evicted, so this method is guaranteed to be called for any item that's removed from the cache. The returned entry must not include any strong references to other entries. See note in the documentation of `LRUMap.prototype.set()`.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frsms%2Fjs-lru","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frsms%2Fjs-lru","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frsms%2Fjs-lru/lists"}