@flupkejs/lru-cache 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +10 -0
- package/src/index.d.ts +10 -0
- package/src/index.js +25 -0
package/package.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@flupkejs/lru-cache",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Map-based LRU cache",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "src/index.d.ts",
|
|
7
|
+
"files": ["src"],
|
|
8
|
+
"exports": { ".": { "types": "./src/index.d.ts", "default": "./src/index.js" }, "./package.json": "./package.json" },
|
|
9
|
+
"license": "MIT"
|
|
10
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
declare class LRUCache<K = unknown, V = unknown> {
|
|
2
|
+
constructor(options?: { max?: number });
|
|
3
|
+
get(key: K): V | undefined;
|
|
4
|
+
set(key: K, val: V): this;
|
|
5
|
+
has(key: K): boolean;
|
|
6
|
+
delete(key: K): boolean;
|
|
7
|
+
clear(): void;
|
|
8
|
+
readonly size: number;
|
|
9
|
+
}
|
|
10
|
+
export = LRUCache;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
module.exports = class LRUCache {
|
|
3
|
+
constructor(options) {
|
|
4
|
+
this.max = options?.max || 1000;
|
|
5
|
+
this.cache = new Map();
|
|
6
|
+
}
|
|
7
|
+
get(key) {
|
|
8
|
+
if (!this.cache.has(key)) return undefined;
|
|
9
|
+
const val = this.cache.get(key);
|
|
10
|
+
this.cache.delete(key);
|
|
11
|
+
this.cache.set(key, val);
|
|
12
|
+
return val;
|
|
13
|
+
}
|
|
14
|
+
set(key, val) {
|
|
15
|
+
if (this.cache.has(key)) this.cache.delete(key);
|
|
16
|
+
else if (this.cache.size >= this.max) this.cache.delete(this.cache.keys().next().value);
|
|
17
|
+
this.cache.set(key, val);
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
has(key) { return this.cache.has(key); }
|
|
21
|
+
delete(key) { return this.cache.delete(key); }
|
|
22
|
+
clear() { this.cache.clear(); }
|
|
23
|
+
*keys() { yield* this.cache.keys(); }
|
|
24
|
+
*values() { yield* this.cache.values(); }
|
|
25
|
+
};
|