Skip to content

Commit 3edb95f

Browse files
committed
refactor(utilities/cache): maxSize for in-memory
1 parent 132156f commit 3edb95f

File tree

3 files changed

+42
-34
lines changed

3 files changed

+42
-34
lines changed

packages/utilities/src/cache-pattern/in-memory.simple.ts

Lines changed: 0 additions & 34 deletions
This file was deleted.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
export class InMemorySimpleCache<T> {
2+
constructor(maxSize?: number) {
3+
if (maxSize && maxSize > 0) {
4+
this.maxSize = maxSize;
5+
}
6+
}
7+
8+
protected memory = new Map<string, T>();
9+
protected maxSize = -1;
10+
11+
get(key: string): T | undefined {
12+
return this.memory.get(key);
13+
}
14+
15+
set(key: string, value: T): void {
16+
this.memory.set(key, value);
17+
18+
if (this.maxSize > 0 && this.size >= this.maxSize) {
19+
const firstKey = this.memory.keys().next();
20+
21+
if (!firstKey.done) {
22+
this.delete(firstKey.value);
23+
}
24+
}
25+
}
26+
27+
delete(key: string): boolean {
28+
return this.memory.delete(key);
29+
}
30+
31+
clearAll(): void {
32+
this.memory.clear();
33+
}
34+
35+
has(key: string): boolean {
36+
return this.memory.has(key);
37+
}
38+
39+
get size(): number {
40+
return this.memory.size;
41+
}
42+
}

0 commit comments

Comments
 (0)