JavaScrip实现一个有时间限制的缓存类

说在前面

🎈探索 JavaScript 中一种基于自动过期机制的时间限制缓存实现方式,提高数据缓存策略的灵活性和效率。

题目描述

编写一个类,它允许获取和设置键-值对,并且每个键都有一个 过期时间 。

该类有三个公共方法:

set(key, value, duration) :接收参数为整型键 key 、整型值 value 和以毫秒为单位的持续时间 duration 。一旦 duration 到期后,这个键就无法访问。如果相同的未过期键已经存在,该方法将返回 true ,否则返回 false 。如果该键已经存在,则它的值和持续时间都应该被覆盖。

get(key) :如果存在一个未过期的键,它应该返回这个键相关的值。否则返回 -1 。

count() :返回未过期键的总数。

示例 1:

ini 复制代码
输入: 
actions = ["TimeLimitedCache", "set", "get", "count", "get"]
values = [[], [1, 42, 100], [1], [], [1]]
timeDeays = [0, 0, 50, 50, 150]
输出: [null, false, 42, 1, -1]
解释:
在 t=0 时,缓存被构造。
在 t=0 时,添加一个键值对 (1: 42) ,过期时间为 100ms 。因为该值不存在,因此返回false。
在 t=50 时,请求 key=1 并返回值 42。
在 t=50 时,调用 count() ,缓存中有一个未过期的键。
在 t=100 时,key=1 到期。
在 t=150 时,调用 get(1) ,返回 -1,因为缓存是空的。

示例 2:

ini 复制代码
输入:
actions = ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"]
values = [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []]
timeDelays = [0, 0, 40, 50, 120, 200, 250]
输出: [null, false, true, 50, 50, -1]
解释:
在 t=0 时,缓存被构造。
在 t=0 时,添加一个键值对 (1: 42) ,过期时间为 50ms。因为该值不存在,因此返回false。
当 t=40 时,添加一个键值对 (1: 50) ,过期时间为 100ms。因为一个未过期的键已经存在,返回 true 并覆盖这个键的旧值。
在 t=50 时,调用 get(1) ,返回 50。
在 t=120 时,调用 get(1) ,返回 50。
在 t=140 时,key=1 过期。
在 t=200 时,调用 get(1) ,但缓存为空,因此返回 -1。
在 t=250 时,count() 返回0 ,因为缓存是空的,没有未过期的键。

提示:

  • 0 <= key, value <= 109
  • 0 <= duration <= 1000
  • 1 <= actions.length <= 100
  • actions.length === values.length
  • actions.length === timeDelays.length
  • 0 <= timeDelays[i] <= 1450
  • actions[i] 是 "TimeLimitedCache"、"set"、"get" 和 "count" 中的一个。
  • 第一个操作始终是 "TimeLimitedCache" 而且一定会以 0 毫秒的延迟立即执行

解题思路

1、构造函数 TimeLimitedCache 创建了一个新的 Map 对象,并将其赋值给实例属性 map

javascript 复制代码
var TimeLimitedCache = function () {
    this.map = new Map();
};

2、set 方法用于向缓存中添加一个键值对,并设置该键值对的过期时间

  • 首先,该方法调用 get 方法检查缓存中是否已存在相同的键,如果存在,则将返回值 res 设置为 false,表示未过期的键已经存在;
  • 然后,创建一个包含 exceedTime 和 value 的对象,其中 exceedTime 表示过期时间,通过当前时间加上指定的持续时间计算得到;
  • 最后,将键值对存储在 map 中,并返回 res。
javascript 复制代码
TimeLimitedCache.prototype.set = function (key, value, duration) {
    let res = true;
    if(this.get(key) == -1) res = false;
    const obj = {
        exceedTime :new Date().getTime() + duration,
        value
    };
    this.map.set(key,obj);
    return res;
};

3、get 方法用于获取指定键的值

  • 首先,通过键从 map 中获取对应的值对象 obj;
  • 如果找不到该键,则返回 -1 表示未找到;
  • 然后,获取值对象中的过期时间 exceedTime;
  • 如果过期时间小于等于当前时间,则表示键已过期,返回 -1;
  • 否则,返回值对象的值。
javascript 复制代码
TimeLimitedCache.prototype.get = function (key) {
    const obj = this.map.get(key);
    if(!obj) return -1;
    const exceedTime = obj.exceedTime;
    if(exceedTime <= new Date().getTime()) return -1;
    return obj.value;
};

4、count 方法用于计算缓存中未过期的键的数量

  • 首先,定义一个变量 cnt 并将其初始化为 0,用于记录未过期的键的数量;
  • 获取当前时间 dateTime;
  • 然后,使用 forEach 方法遍历 map 中的每个值对象 obj;
  • 对于每个值对象,获取其过期时间 exceedTime;
  • 如果过期时间大于当前时间,则将计数器 cnt 加一;
  • 最后,返回计数器 cnt 的值。
javascript 复制代码
TimeLimitedCache.prototype.count = function () {
    let cnt = 0;
    const dateTime = new Date().getTime();
    this.map.forEach(obj=>{
        const exceedTime = obj.exceedTime;
        if(exceedTime > dateTime) cnt++;
    })
    return cnt;
};

AC代码

javascript 复制代码
var TimeLimitedCache = function () {
    this.map = 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) {
    let res = true;
    if(this.get(key) == -1) res = false;
    const obj = {
        exceedTime :new Date().getTime() + duration,
        value
    };
    this.map.set(key,obj);
    return res;
};

/**
 * @param {number} key
 * @return {number} value associated with key
 */
TimeLimitedCache.prototype.get = function (key) {
    const obj = this.map.get(key);
    if(!obj) return -1;
    const exceedTime = obj.exceedTime;
    if(exceedTime <= new Date().getTime()) return -1;
    return obj.value;
};

/**
 * @return {number} count of non-expired keys
 */
TimeLimitedCache.prototype.count = function () {
    let cnt = 0;
    const dateTime = new Date().getTime();
    this.map.forEach(obj=>{
        const exceedTime = obj.exceedTime;
        if(exceedTime > dateTime) cnt++;
    })
    return cnt;
};

/**
 * const timeLimitedCache = new TimeLimitedCache()
 * timeLimitedCache.set(1, 42, 1000); // false
 * timeLimitedCache.get(1) // 42
 * timeLimitedCache.count() // 1
 */

公众号

关注公众号『前端也能这么有趣』,获取更多有趣内容。

说在后面

🎉 这里是 JYeontu,现在是一名前端工程师,有空会刷刷算法题,平时喜欢打羽毛球 🏸 ,平时也喜欢写些东西,既为自己记录 📋,也希望可以对大家有那么一丢丢的帮助,写的不好望多多谅解 🙇,写错的地方望指出,定会认真改进 😊,偶尔也会在自己的公众号『前端也能这么有趣』发一些比较有趣的文章,有兴趣的也可以关注下。在此谢谢大家的支持,我们下文再见 🙌。

相关推荐
ZZZ_O^O25 分钟前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树
CV-King1 小时前
opencv实战项目(三十):使用傅里叶变换进行图像边缘检测
人工智能·opencv·算法·计算机视觉
代码雕刻家1 小时前
数据结构-3.9.栈在递归中的应用
c语言·数据结构·算法
雨中rain1 小时前
算法 | 位运算(哈希思想)
算法
正小安1 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
Kalika0-03 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光3 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   3 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   3 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d