From fcea8fc7a180c3576df5ea5e2a0a75e5f8c05f05 Mon Sep 17 00:00:00 2001 From: dyh_a Date: Tue, 16 Aug 2022 02:00:00 +0800 Subject: [PATCH] =?UTF-8?q?feat(Cache.ts):=20=E6=96=B0=E5=A2=9E`deleteByTa?= =?UTF-8?q?g`=E9=80=9A=E8=BF=87tag=E5=88=A0=E9=99=A4=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Cache.ts | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/Cache.ts b/src/Cache.ts index c732f20..addd214 100644 --- a/src/Cache.ts +++ b/src/Cache.ts @@ -1,14 +1,19 @@ +import type { Tag } from './types'; + /** * @public */ export class Cache { - constructor(protected readonly cache = new Map()) {} + constructor( + protected readonly cache = new Map(), + protected readonly tagMap = new Map>(), + ) {} clearDeadCache() { const now = Date.now(); for (const [k, v] of this.cache.entries()) { if (v.expires > now) continue; - this.cache.delete(k); + this.delete(k); } } @@ -17,19 +22,35 @@ export class Cache { if (!v) return null; const now = Date.now(); if (now > v.expires) { - this.cache.delete(key); + this.delete(key); return null; } return v.value; } - set(key: any, value: V, { timeout = 5 * 1000 }: { timeout?: number } = {}) { - this.cache.set(key, { value, expires: timeout + Date.now() }); + set(key: any, value: V, { timeout = 5 * 1000, tag }: { timeout?: number; tag?: Tag } = {}) { + if (tag) { + if (!this.tagMap.has(tag)) this.tagMap.set(tag, new Set()); + (this.tagMap.get(tag) as Set).add(key); + } + this.cache.set(key, { value, tag, expires: timeout + Date.now() }); this.clearDeadCache(); } delete(key: any) { + const value = this.cache.get(key); this.cache.delete(key); + if (value?.tag) { + this.tagMap.get(value.tag)?.delete(key); + } + } + + deleteByTag(tag: Tag) { + const keys = this.tagMap.get(tag); + keys?.forEach((key) => { + this.cache.delete(key); + }); + this.tagMap.delete(tag); } has(key: any): boolean {