有时间限制的缓存

题目链接:

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
 */
相关推荐
蓝胖的四次元口袋11 小时前
Redis知识梳理(1)
数据库·redis·缓存
wefg112 小时前
【Redis】C++ 自定义客户端
数据库·redis·缓存
一个有温度的技术博主15 小时前
两级缓存一致性实战:Redis + 本地缓存,如何不让数据“分裂”?
redis·spring·缓存
linweidong19 小时前
Redis 集群故障排查与修复实战:从 Connection refused 到内存打满的七个现场
运维·数据库·redis·缓存·redis集群·运维面经·实施面经
星夜离尘5620 小时前
FIFO深度怎么定?用突发流量和背压算清缓存预算
缓存·fpga开发·verilog·fifo·背压
kyle~20 小时前
软件缓存一致性
缓存
仍然.1 天前
Redis---缓存
数据库·redis·缓存
骇客野人1 天前
微服务多级缓存架构设计
缓存·微服务·架构
禾小西2 天前
05丨Redis 内存快照:宕机后,如何实现快速恢复?
数据库·redis·缓存