有时间限制的缓存

题目链接:

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
 */
相关推荐
ashiho19 小时前
【Redis】原理篇 3w字详解
数据库·redis·缓存·bootstrap
轻揉小乔 真新人1 天前
使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
运维·nginx·缓存
小园子的小菜2 天前
Redis 核心原理深度解析:从数据结构、IO 模型到持久化机制
数据库·redis·缓存
BullSmall2 天前
Another Redis Desktop Manager(ARDM)下载指南
数据库·redis·缓存
nvd113 天前
ArgoCD 双层轮询深入拆解:从 redis-app.yaml 注册到缓存重建的完整链路
redis·缓存·argocd
xiaoxiangsiyan3 天前
LNMP + Redis Sentinel 高可用架构部署手册(续)
运维·网络·数据库·redis·缓存·架构·sentinel
難釋懷3 天前
Nginx外置缓存-redis2-nginx-module
nginx·缓存·junit
LearnYard3 天前
Android存储空间清理策略对比:缓存识别与多种清理方案的技术分析
缓存·智能手机
时空自由民.3 天前
STM32的缓存Cache
stm32·嵌入式硬件·缓存
Sam_Deep_Thinking3 天前
如何维持缓存的一致性?
java·缓存·面试·程序员·系统架构