有时间限制的缓存

题目链接:

2622. 有时间限制的缓存 - 力扣(LeetCode)

思路:

构建一个 map ,并利用 setTimeout 思想,到了对应的 duration 后 去删除对应 map 的 key 对应的值,我们存入 map 里面的值 包含 value 本身 和 setTimeout 返回的 一个数字

这里需要注意 我本身是采用 中括号形式去访问对象,但是leetcode 不能采用这种方式,大家老老实实采用 . 访问吧

代码:

javascript 复制代码
var TimeLimitedCache = function () {
    this.cache = new Map()
};

/** 
 * @param {number} key
 * @param {number} value
 * @param {number} duration time until expiration in ms
 * @return {boolean} if un-expired key already existed
 */
TimeLimitedCache.prototype.set = function (key, value, duration) {
    const valueInCache = this.cache.get(key)
    if (valueInCache) {
        clearTimeout(valueInCache.timeout)
    }
    let timeout = setTimeout(() => this.cache.delete(key), duration)
    this.cache.set(key, { value, timeout })
    return Boolean(valueInCache)
};

/** 
 * @param {number} key
 * @return {number} value associated with key
 */
TimeLimitedCache.prototype.get = function (key) {
    if (this.cache.has(key)) return this.cache.get(key).value
    else return -1
};

/** 
 * @return {number} count of non-expired keys
 */
TimeLimitedCache.prototype.count = function () {
    return this.cache.size
};

/**
 * const timeLimitedCache = new TimeLimitedCache()
 * timeLimitedCache.set(1, 42, 1000); // false
 * timeLimitedCache.get(1) // 42
 * timeLimitedCache.count() // 1
 */
相关推荐
EmbeddedCore13 小时前
模块化编程实践:一种面向蓝牙少量数据分包传输的轻量级缓存管理方案
缓存
lifewange13 小时前
Redis的测试要点和测试方法
数据库·redis·缓存
李白的天不白15 小时前
‌在下载webpack出现certificate has expired‌问题 清除缓存
缓存
qqacj17 小时前
Redis设置密码
数据库·redis·缓存
PiaoShiSun19 小时前
小米手机浏览器缓存视频如何导出
缓存·智能手机·音视频
终端鹿19 小时前
动态组件 & keep-alive 缓存策略与性能优化
缓存·性能优化
1104.北光c°21 小时前
【重写优化 新增绘图】布谷鸟过滤器:布隆过滤器的更优缓存穿透解?
java·开发语言·后端·缓存·缓存穿透·布隆过滤器·布谷鸟过滤器
希望永不加班1 天前
SpringBoot 整合 Redis 缓存
spring boot·redis·后端·缓存·wpf
zz-zjx1 天前
redis手动安装主从+哨兵
数据库·redis·缓存
小羊在睡觉1 天前
Reids缓存穿透、击穿、雪崩
redis·缓存·go