---
# System prepended metadata

title: 2622. Cache With Time Limit

---

# [2622. Cache With Time Limit](https://leetcode.com/problems/cache-with-time-limit/description/?envType=study-plan-v2&envId=30-days-of-javascript)
![image](https://hackmd.io/_uploads/rJutGNgSC.png)
![image](https://hackmd.io/_uploads/BJ-9zNlBR.png)
這一條要求我們cache一個class
並要求要有3大功能
set(key,value,duration)
get(key)
count
由於需要放置key,value 所以我們將cache定義為map
利用map的特性來set key跟value要包含timeout
並在指定時間後刪除這個key
```js
const TimeLimitedCache = function() {
    this.cache = new Map();  // Using Map so we don't need a size variable
};

TimeLimitedCache.prototype.set = function(key, value, duration) {
    let found = this.cache.has(key);
    if (found) clearTimeout(this.cache.get(key).ref);  // Cancel previous timeout
    this.cache.set(key, {
        value,  // Equivalent to `value: value`
        ref: setTimeout(() => this.cache.delete(key), duration)
    });
    return found;
};

TimeLimitedCache.prototype.get = function(key) {
    return this.cache.has(key) ? this.cache.get(key).value : -1;
};

TimeLimitedCache.prototype.count = function() {
    return this.cache.size;
};
```
