有时间限制的缓存

题目链接:

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
 */
相关推荐
W23035765737 小时前
C++ 高并发线程池实战(二):动态缓存线程池 + 调用者运行拒绝策略完整版实现
开发语言·c++·缓存
roman_日积跬步-终至千里9 小时前
【系统架构师案例题-知识点】数据库与缓存设计
数据库·缓存·系统架构
_Evan_Yao11 小时前
缓存金字塔上的红色闪电:Redis 如何借力 CPU 的 L1/L2/L3 与 TLB 飞驰
java·数据库·redis·后端·缓存
弹简特12 小时前
【Redis】01-认识Redis+分布式系统知识背景介绍
数据库·redis·缓存
他们叫我阿冠12 小时前
SpringAI的基础学习
数据库·redis·缓存
深念Y14 小时前
大模型API缓存的底层原理:从显存到网关
缓存·ai·llm·api·硬件·显存·kvcache
赵优秀一一15 小时前
Redis 基础、缓存、String/Hash
redis·缓存·哈希算法
字节高级特工16 小时前
迈入Redis:持久化
数据库·redis·缓存
人道领域18 小时前
【Redis实战篇】初步基于Redis实现的分布式锁---基于黑马点评
java·数据库·redis·分布式·缓存
Lyyaoo.1 天前
Redis基础
数据库·redis·缓存