From 6ff8c8d290feae9dec474ab4ae00b4f390f99fcc Mon Sep 17 00:00:00 2001 From: Dragory <2606411+Dragory@users.noreply.github.com> Date: Sun, 13 Oct 2019 00:20:59 +0300 Subject: [PATCH] SimpleCache: allow specifying max items, add better type support --- src/SimpleCache.ts | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/SimpleCache.ts b/src/SimpleCache.ts index a06d8d12..bf53f936 100644 --- a/src/SimpleCache.ts +++ b/src/SimpleCache.ts @@ -2,15 +2,19 @@ import Timeout = NodeJS.Timeout; const CLEAN_INTERVAL = 1000; -export class SimpleCache { - protected readonly retentionTime; +export class SimpleCache { + protected readonly retentionTime: number; + protected readonly maxItems: number; + protected cleanTimeout: Timeout; protected unloaded: boolean; - protected store: Map; + protected store: Map; - constructor(retentionTime) { + constructor(retentionTime: number, maxItems?: number) { this.retentionTime = retentionTime; + this.maxItems = maxItems; + this.store = new Map(); } @@ -32,14 +36,19 @@ export class SimpleCache { } } - set(key: string, value) { + set(key: string, value: T) { this.store.set(key, { remove_at: Date.now() + this.retentionTime, value, }); + + if (this.maxItems && this.store.size > this.maxItems) { + const keyToDelete = this.store.keys().next().value; + this.store.delete(keyToDelete); + } } - get(key: string) { + get(key: string): T { const info = this.store.get(key); if (!info) return null;