Skip to content

Commit c4718c1

Browse files
day 17 task complete
1 parent 70f8847 commit c4718c1

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

day17/leetcode2622.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 2622. Cache With Time Limit
2+
// URL -> https://leetcode.com/problems/cache-with-time-limit/
3+
4+
5+
var TimeLimitedCache = function () {
6+
// this.cache = {}
7+
// this.count = 0;
8+
this.cache = new Map()
9+
};
10+
11+
/**
12+
* @param {number} key
13+
* @param {number} value
14+
* @param {number} duration time until expiration in ms
15+
* @return {boolean} if un-expired key already existed
16+
*/
17+
TimeLimitedCache.prototype.set = function (key, value, duration) {
18+
const alreadyExists = this.cache.get(key)
19+
20+
if (alreadyExists) {
21+
clearTimeout(alreadyExists.timeoutId);
22+
}
23+
const timeoutId = setTimeout(() => {
24+
this.cache.delete(key);
25+
}, duration)
26+
this.cache.set(key, { value, timeoutId });
27+
return Boolean(alreadyExists);
28+
};
29+
30+
/**
31+
* @param {number} key
32+
* @return {number} value associated with key
33+
*/
34+
TimeLimitedCache.prototype.get = function (key) {
35+
return this.cache.has(key) ? this.cache.get(key).value : -1;
36+
};
37+
38+
/**
39+
* @return {number} count of non-expired keys
40+
*/
41+
TimeLimitedCache.prototype.count = function () {
42+
return this.cache.size;
43+
};
44+
45+
/**
46+
* const timeLimitedCache = new TimeLimitedCache()
47+
* timeLimitedCache.set(1, 42, 1000); // false
48+
* timeLimitedCache.get(1) // 42
49+
* timeLimitedCache.count() // 1
50+
*/

0 commit comments

Comments
 (0)