From 4d950b7618829d61df64687626420ba3800149c3 Mon Sep 17 00:00:00 2001 From: pengzhanbo Date: Sun, 25 Feb 2024 00:44:20 +0800 Subject: [PATCH] =?UTF-8?q?perf(plugin-shikiji):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=BC=80=E5=8F=91=E6=97=B6=E7=BC=96=E8=AF=91=E9=80=9F=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/plugin-shikiji/src/node/lru.ts | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 plugins/plugin-shikiji/src/node/lru.ts diff --git a/plugins/plugin-shikiji/src/node/lru.ts b/plugins/plugin-shikiji/src/node/lru.ts new file mode 100644 index 000000000..191a6f0c2 --- /dev/null +++ b/plugins/plugin-shikiji/src/node/lru.ts @@ -0,0 +1,39 @@ +// adapted from https://stackoverflow.com/a/46432113/11613622 + +export class LRUCache { + private max: number + private cache: Map + + constructor(max: number = 10) { + this.max = max + this.cache = new Map() + } + + get(key: K): V | undefined { + const item = this.cache.get(key) + if (item !== undefined) { + // refresh key + this.cache.delete(key) + this.cache.set(key, item) + } + return item + } + + set(key: K, val: V): void { + // refresh key + if (this.cache.has(key)) + this.cache.delete(key) + // evict oldest + else if (this.cache.size === this.max) + this.cache.delete(this.first()!) + this.cache.set(key, val) + } + + first(): K | undefined { + return this.cache.keys().next().value + } + + clear(): void { + this.cache.clear() + } +}