SimpleCache: allow specifying max items, add better type support
This commit is contained in:
parent
a0a30add2b
commit
6ff8c8d290
1 changed files with 15 additions and 6 deletions
|
@ -2,15 +2,19 @@ import Timeout = NodeJS.Timeout;
|
|||
|
||||
const CLEAN_INTERVAL = 1000;
|
||||
|
||||
export class SimpleCache {
|
||||
protected readonly retentionTime;
|
||||
export class SimpleCache<T = any> {
|
||||
protected readonly retentionTime: number;
|
||||
protected readonly maxItems: number;
|
||||
|
||||
protected cleanTimeout: Timeout;
|
||||
protected unloaded: boolean;
|
||||
|
||||
protected store: Map<string, { remove_at: number; value: any }>;
|
||||
protected store: Map<string, { remove_at: number; value: T }>;
|
||||
|
||||
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;
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue