|
1 | | -import { container } from 'tsyringe'; |
2 | | -import ClearExpiredEntriesInSetsWithTtlTask from '../task_queue/tasks/ClearExpiredEntriesInSetsWithTtlTask.js'; |
| 1 | +import MapWithTtl from '../util/MapWithTtl.js'; |
3 | 2 |
|
4 | 3 | export default class SetWithTtl<T> { |
5 | | - private readonly values = new Map<T, number>(); |
6 | | - private readonly ttlInMilliseconds: number; |
| 4 | + private readonly values: MapWithTtl<T, null>; |
7 | 5 |
|
8 | | - private constructor(ttlInSeconds: number) { |
9 | | - this.ttlInMilliseconds = ttlInSeconds * 1000; |
| 6 | + constructor(ttlInSeconds: number) { |
| 7 | + this.values = MapWithTtl.create(ttlInSeconds); |
10 | 8 | } |
11 | 9 |
|
12 | 10 | add(key: T): void { |
13 | | - this.values.set(key, Date.now() + this.ttlInMilliseconds); |
| 11 | + this.values.set(key, null); |
14 | 12 | } |
15 | 13 |
|
16 | 14 | has(key: T): boolean { |
17 | | - const expiration = this.values.get(key); |
18 | | - return expiration != null && !this.isExpired(expiration); |
| 15 | + return this.values.has(key); |
19 | 16 | } |
20 | 17 |
|
21 | 18 | getAgeInSeconds(key: T): number { |
22 | | - const expiration = this.values.get(key); |
23 | | - if (expiration == null || this.isExpired(expiration)) { |
24 | | - return 0; |
25 | | - } |
26 | | - |
27 | | - const creationTime = expiration - this.ttlInMilliseconds; |
28 | | - return Math.floor((Date.now() - creationTime) / 1000); |
| 19 | + return this.values.getAgeInSeconds(key); |
29 | 20 | } |
30 | 21 |
|
31 | 22 | clear(): void { |
32 | 23 | this.values.clear(); |
33 | 24 | } |
34 | 25 |
|
35 | 26 | clearExpired(): void { |
36 | | - for (const [value, expiration] of this.values.entries()) { |
37 | | - if (this.isExpired(expiration)) { |
38 | | - this.values.delete(value); |
39 | | - } |
40 | | - } |
41 | | - } |
42 | | - |
43 | | - private isExpired(expiration: number): boolean { |
44 | | - return expiration < Date.now(); |
45 | | - } |
46 | | - |
47 | | - static create<T>(ttlInSeconds: number): SetWithTtl<T> { |
48 | | - const setWithTTL = new SetWithTtl<T>(ttlInSeconds); |
49 | | - container.resolve(ClearExpiredEntriesInSetsWithTtlTask).registerSet(setWithTTL); |
50 | | - return setWithTTL; |
| 27 | + this.values.clearExpired(); |
51 | 28 | } |
52 | 29 | } |
0 commit comments