File tree 1 file changed +50
-0
lines changed
1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments