有时间限制的缓存

题目链接:

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
 */
相关推荐
晚风_END4 小时前
Linux|操作系统|最新版zfs编译后的适用于centos7的rpm安装包完全离线安装介绍
linux·运维·服务器·c++·python·缓存·github
189228048615 小时前
NV301固态MT29F32T08GWLBHD6-QJES:B
大数据·服务器·人工智能·科技·缓存
YIN_尹5 小时前
关于论文《FLUSH+RELOAD:一种高分辨率、低噪声的L3缓存侧信道攻击》的理解
安全·缓存·系统安全·缓存侧信道攻击
Mahir086 小时前
Redis 分布式锁与 Redisson 深度解析:从原生实现到工业级解决方案
数据库·redis·分布式·缓存·面试
看我干嘛!6 小时前
Redis安装
数据库·redis·缓存
189228048617 小时前
NV266固态MT29F32T08GSLBHL8-36QMES:B
大数据·服务器·人工智能·科技·缓存
爱编程的小新☆7 小时前
Langchain4j对话记忆
数据库·缓存·持久化存储·langchain4j
oddsand17 小时前
原理篇-Redis数据结构
数据库·redis·缓存
phltxy18 小时前
Redis 事务
数据库·redis·缓存
1892280486120 小时前
NV265固态MT29F32T08GSLBHL8-24QMES:B
大数据·服务器·人工智能·科技·缓存