思路:
使用Map + 定时器来解决,我们可以创建一个Map,在set()方法中先判断Map中是否有还未过期的键值对,如果存在,先清掉之前设置的定时器,防止之前的定时器将当前设置的键值对删掉,然后再设置新的定时器,定时器的作用就是经过duration毫秒后,删掉当前键值对,就代表它过期了。
TypeScript代码:
class TimeLimitedCache {
private timeMap: Map<number, {
val: number,
timer: ReturnType<typeof setTimeout>
}>;
constructor() {
this.timeMap = new Map();
}
set(key: number, value: number, duration: number): boolean {
const flag: boolean = this.timeMap.has(key);
if(flag) {
clearTimeout(this.timeMap.get(key).timer);
}
this.timeMap.set(key, {
val: value,
timer: setTimeout(() => {
this.timeMap.delete(key);
}, duration)
});
return flag;
}
get(key: number): number {
return this.timeMap.has(key) ? this.timeMap.get(key).val : -1;
}
count(): number {
return this.timeMap.size;
}
}
/**
* Your TimeLimitedCache object will be instantiated and called as such:
* var obj = new TimeLimitedCache()
* obj.set(1, 42, 1000); // false
* obj.get(1) // 42
* obj.count() // 1
*/