Gathering detailed insights and metrics for lru_map
Gathering detailed insights and metrics for lru_map
Gathering detailed insights and metrics for lru_map
Gathering detailed insights and metrics for lru_map
A fast, simple & universal Least Recently Used (LRU) map for JavaScript
npm install lru_map
Typescript
Module System
Node Version
NPM Version
JavaScript (89.7%)
HTML (9.53%)
TypeScript (0.78%)
Total Downloads
632,510,853
Last Day
111,925
Last Week
2,223,968
Last Month
9,714,024
Last Year
122,514,544
MIT License
793 Stars
78 Commits
89 Forks
16 Watchers
3 Branches
11 Contributors
Updated on Jun 26, 2025
Minified
Minified + Gzipped
Latest Version
0.4.1
Package Id
lru_map@0.4.1
Size
8.38 kB
NPM Version
6.14.8
Node Version
14.11.0
Published on
Oct 22, 2020
Cumulative downloads
Total Downloads
Last Day
-19%
111,925
Compared to previous day
Last Week
-12.1%
2,223,968
Compared to previous week
Last Month
4.1%
9,714,024
Compared to previous month
Last Year
-28.4%
122,514,544
Compared to previous year
2
A finite key-value map using the Least Recently Used (LRU) algorithm, where the most recently-used items are "kept alive" while older, less-recently used items are evicted to make room for newer items.
Useful when you want to limit use of memory to only hold commonly-used things.
Based on a doubly-linked list for low complexity random shuffling of entries.
The cache object iself has a "head" (least recently used entry) and a "tail" (most recently used entry).
The "oldest" and "newest" are list entries -- an entry might have a "newer" and an "older" entry (doubly-linked, "older" being close to "head" and "newer" being closer to "tail").
Key lookup is done through a key-entry mapping native object, which on most
platforms mean O(1)
complexity. This comes at a very low memory cost (for
storing two extra pointers for each entry).
Fancy ASCII art illustration of the general design:
1 entry entry entry entry 2 ______ ______ ______ ______ 3 | head |.newer => | |.newer => | |.newer => | tail | 4.oldest = | A | | B | | C | | D | = .newest 5 |______| <= older.|______| <= older.|______| <= older.|______| 6 7 removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added
1let c = new LRUMap(3) 2c.set('adam', 29) 3c.set('john', 26) 4c.set('angela', 24) 5c.toString() // -> "adam:29 < john:26 < angela:24" 6c.get('john') // -> 26 7 8// Now 'john' is the most recently used entry, since we just requested it 9c.toString() // -> "adam:29 < angela:24 < john:26" 10c.set('zorro', 141) // -> {key:adam, value:29} 11 12// Because we only have room for 3 entries, adding 'zorro' caused 'adam' 13// to be removed in order to make room for the new entry 14c.toString() // -> "angela:24 < john:26 < zorro:141"
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".
Using NPM: yarn add lru_map
(note that because NPM is one large flat namespace, you need to import the module as "lru_map" rather than simply "lru".)
Using AMD: An AMD module loader like amdld
can be used to load this module as well. There should be nothing to configure.
Testing:
npm test
npm run benchmark
ES compatibility: This implementation is compatible with modern JavaScript environments and depend on the following features not found in ES5:
const
and let
keywordsSymbol
including Symbol.iterator
Map
Note: If you need ES5 compatibility e.g. to use with older browsers, please use version 2 which has a slightly less feature-full API but is well-tested and about as fast as this implementation.
Using with TypeScript
This 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
.
1import {LRUMap} from './lru' 2// import {LRUMap} from 'lru' // when using via AMD 3// import {LRUMap} from 'lru_map' // when using from NPM 4console.log('LRUMap:', LRUMap)
The API imitates that of Map
, which means that in most cases you can use LRUMap
as a drop-in replacement for Map
.
1export class LRUMap<K,V> { 2 // Construct a new cache object which will hold up to limit entries. 3 // When the size == limit, a `put` operation will evict the oldest entry. 4 // 5 // If `entries` is provided, all entries are added to the new map. 6 // `entries` should be an Array or other iterable object whose elements are 7 // key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. 8 // null is treated as undefined. 9 constructor(limit :number, entries? :Iterable<[K,V]>); 10 11 // Convenience constructor equivalent to `new LRUMap(count(entries), entries)` 12 constructor(entries :Iterable<[K,V]>); 13 14 // Current number of items 15 size :number; 16 17 // Maximum number of items this map can hold 18 limit :number; 19 20 // Least recently-used entry. Invalidated when map is modified. 21 oldest :Entry<K,V>; 22 23 // Most recently-used entry. Invalidated when map is modified. 24 newest :Entry<K,V>; 25 26 // Replace all values in this map with key-value pairs (2-element Arrays) from 27 // provided iterable. 28 assign(entries :Iterable<[K,V]>) : void; 29 30 // Put <value> into the cache associated with <key>. Replaces any existing entry 31 // with the same key. Returns `this`. 32 set(key :K, value :V) : LRUMap<K,V>; 33 34 // Purge the least recently used (oldest) entry from the cache. 35 // Returns the removed entry or undefined if the cache was empty. 36 shift() : [K,V] | undefined; 37 38 // Get and register recent use of <key>. 39 // Returns the value associated with <key> or undefined if not in cache. 40 get(key :K) : V | undefined; 41 42 // Check if there's a value for key in the cache without registering recent use. 43 has(key :K) : boolean; 44 45 // Access value for <key> without registering recent use. Useful if you do not 46 // want to chage the state of the map, but only "peek" at it. 47 // Returns the value associated with <key> if found, or undefined if not found. 48 find(key :K) : V | undefined; 49 50 // Remove entry <key> from cache and return its value. 51 // Returns the removed value, or undefined if not found. 52 delete(key :K) : V | undefined; 53 54 // Removes all entries 55 clear() : void; 56 57 // Returns an iterator over all keys, starting with the oldest. 58 keys() : Iterator<K>; 59 60 // Returns an iterator over all values, starting with the oldest. 61 values() : Iterator<V>; 62 63 // Returns an iterator over all entries, starting with the oldest. 64 entries() : Iterator<[K,V]>; 65 66 // Returns an iterator over all entries, starting with the oldest. 67 [Symbol.iterator]() : Iterator<[K,V]>; 68 69 // Call `fun` for each entry, starting with the oldest entry. 70 forEach(fun :(value :V, key :K, m :LRUMap<K,V>)=>void, thisArg? :any) : void; 71 72 // Returns an object suitable for JSON encoding 73 toJSON() : Array<{key :K, value :V}>; 74 75 // Returns a human-readable text representation 76 toString() : string; 77} 78 79// An entry holds the key and value, and pointers to any older and newer entries. 80// Entries might hold references to adjacent entries in the internal linked-list. 81// Therefore you should never store or modify Entry objects. Instead, reference the 82// key and value of an entry when needed. 83interface Entry<K,V> { 84 key :K; 85 value :V; 86}
If 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:
1let c = new LRUMap(123); 2c.shift = function() { 3 let entry = LRUMap.prototype.shift.call(this); 4 doSomethingWith(entry); 5 return entry; 6}
The 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()
.
Copyright (c) 2010-2016 Rasmus Andersson https://rsms.me/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
Found 4/27 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More