-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
container.ts
52 lines (44 loc) · 1.34 KB
/
container.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Container, Data, SetOptions } from "./types.ts";
export function createContainer(): Container {
const objects = new Map<string, Data>();
return {
size: () => objects.size,
clear: () => objects.clear(),
delete: (key: string) => objects.delete(key),
set: <T>(
key: string,
value: T,
options?: SetOptions,
) => {
const expirySeconds = options && options.expirySeconds
? options.expirySeconds
: 10;
const isExpired = options && options.isExpired
? options?.isExpired
: false;
const expiryTime = Date.now() + expirySeconds * 1000;
const object: Data = { key, value, isExpired, expiryTime };
if (isExpired) {
const timeoutId = setTimeout(() => {
removeExpiredObject(object);
}, expirySeconds * 1000);
object.timeoutId = timeoutId;
}
objects.set(key, object);
},
get: <T>(key: string) => {
const object = objects.get(key);
if (object && !object.isExpired) return <T> object.value;
else if (object && object.isExpired && object.expiryTime > Date.now()) {
return <T> object.value;
}
return null;
},
};
function removeExpiredObject(object: Data) {
if (object.timeoutId) {
clearTimeout(object.timeoutId);
}
objects.delete(object.key);
}
}