有时间限制的缓存

题目链接:

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
 */
相关推荐
匀泪2 小时前
云原生(Redis配置)
数据库·redis·缓存
北京地铁1号线2 小时前
快手面试题:LRU缓存
缓存·lru
lqj_本人3 小时前
基于 openYuanrong 的生成式推荐缓存高可用方向验证实践
前端·vue.js·缓存
lhbian3 小时前
redis分页查询
数据库·redis·缓存
We་ct3 小时前
React 中的双缓存 Fiber 树机制
前端·react.js·缓存·前端框架·reactjs·fiber·缓存机制
X-⃢_⃢-X3 小时前
八、Redis之BigKey
数据库·redis·缓存
~莫子3 小时前
Redis
数据库·redis·缓存
jgyzl13 小时前
2026.3.9 Redis内存回收内存淘汰
数据库·redis·缓存
-Da-18 小时前
【操作系统学习日记】《现代处理器性能的三重奏:ISA架构、流水线与缓存系统》
后端·缓存·架构·系统架构