有时间限制的缓存
题目
编写一个类,它允许获取和设置键值对,但是每个键都有缓存时间。
set
: 如果存在返回true,否则返回false。当不存在的时候,为这个类新增一个对应的值并添加缓存时间,否则刷新已有的缓存并覆盖新的值,缓存时间到了之后,这个值不允许再被访问。
get
: 如果存在放回它的value,否则返回-1
count
:返回已有缓存且未过期的key的数目
题解
- 首先,类内部可以使用
Map
实现键值对的存储,基础的三个api也可以基于Map
的api:set, get, size
实现 - 缓存过期问题:可以通过
setTimeout
实现新增缓存,也可以通过clearTimeout
实现重置缓存,当缓存过期后Map.prototype.delete
删除即可
代码
js
const TimeLimitedCache = function () {
this.map = new Map();
this.timers = {};
}
TimeLimitedCache.prototype.set = function(key, value, duration) {
const res = this.map.has(key); // 判断是否已存在
this.map.set(key, value); // 加入缓存Map中,如果已存在则覆盖
clearTimeout(this.timers[key]); // 清空缓存对应的timer
this.timers[key] = setTimeout(()=>{
this.map.delete(key);
}, duration);
return res;
}
TimeLimitedCache.prototype.get = function(key) {
const res = this.map.get(key);
return res ? res : -1;
}
TimeLimitedCache.prototype.count = function() {
return this.map.size;
}
const TimeLimitedCache = function () {
this.map = new Map();
this.timers = {};
}
TimeLimitedCache.prototype.set = function(key, value, duration) {
const res = this.map.has(key); // 判断是否已存在
this.map.set(key, value); // 加入缓存Map中,如果已存在则覆盖
clearTimeout(this.timers[key]); // 清空缓存对应的timer
this.timers[key] = setTimeout(()=>{
this.map.delete(key);
}, duration);
return res;
}
TimeLimitedCache.prototype.get = function(key) {
const res = this.map.get(key);
return res ? res : -1;
}
TimeLimitedCache.prototype.count = function() {
return this.map.size;
}