MCPcopy Create free account
hub / github.com/chronark/highstorm / InMemoryCache

Class InMemoryCache

apps/web/lib/cache.ts:1–33  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1export class InMemoryCache<TValue> {
2 public readonly ttl: number;
3 private readonly map: Map<string, { exp: number; value: TValue }>;
4 constructor(opts: { ttl: number }) {
5 this.ttl = opts.ttl;
6 this.map = new Map();
7
8 setInterval(() => {
9 const now = Date.now();
10 this.map.forEach(({ exp }, key) => {
11 if (exp < now) {
12 this.map.delete(key);
13 }
14 });
15 }, 60_000);
16 }
17
18 public set(key: string, value: TValue) {
19 this.map.set(key, { exp: Date.now() + this.ttl, value });
20 }
21
22 public get(key: string): TValue | null {
23 const data = this.map.get(key);
24 if (!data) {
25 return null;
26 }
27 if (data.exp < Date.now()) {
28 this.map.delete(key);
29 return null;
30 }
31 return data.value;
32 }
33}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected