-
Notifications
You must be signed in to change notification settings - Fork 0
/
LocalStorageWithExpiration.ts
45 lines (42 loc) · 1.18 KB
/
LocalStorageWithExpiration.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
const getTimeKey = (key: string) => {
return `${key}_time`;
};
const myLocalStorage = {
setItem: (key: string, value: any, time?: number) => {
localStorage.setItem(key, value);
if (time !== undefined) {
//save expiration time
const curr = Date.now() + time;
localStorage.setItem(getTimeKey(key), curr.toString());
} else {
localStorage.setItem(getTimeKey(key), "NO_TIME");
}
},
getItem: (key: string) => {
const timekey = getTimeKey(key);
const timeInMs = localStorage.getItem(timekey);
if (timeInMs) {
//if time is present then...
const curr = Date.now();
if (timeInMs === "NO_TIME") {
return localStorage.getItem(key);
}
if (+timeInMs > curr) {
//if time is not expired yet then return the value.
return localStorage.getItem(key);
} else {
//if time is expired then remove values and return null
localStorage.removeItem(key);
localStorage.removeItem(timekey);
}
}
return null;
},
removeItem(key: string) {
localStorage.removeItem(key);
localStorage.removeItem(getTimeKey(key));
},
clear() {
localStorage.clear();
},
};