有时间限制的缓存

题目链接:

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
 */
相关推荐
HanhahnaH13 小时前
Redis单线程和Tair多线程架构设计对比
分布式·缓存
wdfk_prog18 小时前
ROS教程07:从 ros::start() 顺着源码读懂 Master、XML-RPC 与 Topic 注册发现
运维·缓存·docker·容器·ros
Escalating_xu19 小时前
【内存管理发展史】从 8086 实模式到分页:CPU 如何把虚拟地址变成物理地址
linux·缓存
wdfk_prog20 小时前
用 Git Submodule + Sparse Checkout 管理 RT-Thread:内核、BSP、第三方库与业务代码分层实践
运维·缓存·docker·容器·ros
努力努力再努力wz20 小时前
【Docker入门系列】镜像为什么能复用?一文吃透 Docker Image、Registry、运行时架构与常用命令
缓存·docker·容器
shark-chili1 天前
关于AI辅助编程的认知
数据库·人工智能·redis·macos·缓存
oioihoii1 天前
在 Kubernetes 上管好数据库:金仓 KES-Operator 正式落地
缓存
wdfk_prog1 天前
ROS教程06:ROS1 Node 启动与停止流程
运维·缓存·docker·容器·ros
Doris__HE1 天前
【元脑服务器NF8480G7-NF8480M7技术规格分享】
运维·服务器·数据库·缓存·性能优化
吉甫作诵2 天前
Redis 常用命令大全:11 大类命令速查手册
运维·数据库·redis·缓存·nosql