力扣前端leetcode 2622.有时间限制的缓存 语言TypeScript(详细分析)TS

文章目录

  • 前言
  • 题目
  • 方法一:setTimeout + clearTimeout + 类语法
    • 解析
    • 方法二:时间戳
      • 解析

        前言

        力扣题目:2622.有时间限制的缓存

        语言:TypeScript

        本文是该题目的众多方法之二

        如果内容有不对的地方,恳请指正


        题目

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

        该类有三个公共方法:

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

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

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

        示例 1:

        输入:

        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:

        输入:

        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 毫秒的延迟立即执行

        方法一:setTimeout + clearTimeout + 类语法

        该方法使用了setTimeout和clearTimeout两个javascripts的内置函数

        type MapEntry = {value: number, timeout: NodeJS.Timeout};
        class TimeLimitedCache { cache = new Map();
            
            set(key: number, value: number, duration: number): Boolean { //set函数中的set和get是Map对象中的方法,而不是TimeLimitedCache的方法
                const timeout = setTimeout(() => this.cache.delete(key), duration);
                const valueInCache = this.cache.get(key);
                if(valueInCache){ clearTimeout(valueInCache.timeout);  //如果缓存中已经有该key,则删除他的计时器
                }
                this.cache.set(key,{value, timeout});    //往缓存中添加键值对
                return Boolean(valueInCache);    //如果之前已有该键,则返回true
            }
            
            get(key: number): number { return this.cache.get(key) ? this.cache.get(key).value : -1;
            }
            
            count(): number { return this.cache.size;
            }
        }
        

        解析

        cache = new Map()
        

        在 TypeScript 中,你可以使用 Map 类来创建一个键值对的映射,这个映射可以存储任意类型的键和值。


        type MapEntry = {value: number, timeout: NodeJS.Timeout};
        

        MapEntry 类型定义了一个对象,该对象具有两个属性:

        value:表示该条目的值,类型为 number。

        timeout:表示与该条目相关联的计时器,类型为 NodeJS.Timeout。


        set(key: number, value: number, duration: number): Boolean { //set函数中的set和get是Map对象中的方法,而不是TimeLimitedCache的方法
                const timeout = setTimeout(() => this.cache.delete(key), duration);
                const valueInCache = this.cache.get(key);
                if(valueInCache){ clearTimeout(valueInCache.timeout);  //如果缓存中已经有该key,则删除他的计时器
                }
                this.cache.set(key,{value, timeout});    //往缓存中添加键值对
                return Boolean(valueInCache);    //如果之前已有该键,则返回true
            }
        

        set方法中,首先声明了timeout作为定时器,用于在指定的时间间隔后执行指定的操作(在 duration 毫秒后删除缓存中的键值对),然后声明了常量valueInCache = this.cache.get(key),首先要明白的事情是,这里的get是Map对象中的方法,在 Map 中,get 是一个方法,用于根据指定的键获取对应的值,而不是类TimeLimitedCache中的get方法。题外话,如果你疑问在 TimeLimitedCache 类中使用自己的 set 方法。在你的 TimeLimitedCache 类中,你可以将 cache 定义为私有成员。

        private cache = new Map();
        

        接着根据题目:一旦 duration 到期后,这个键就无法访问。如果相同的未过期键已经存在,该方法将返回 true ,否则返回 false 。如果该键已经存在,则它的值和持续时间都应该被覆盖。写出代码:

        if(valueInCache){ clearTimeout(valueInCache.timeout);  //如果缓存中已经有该key,则删除他的计时器
                }
                this.cache.set(key,{value, timeout});    //往缓存中添加键值对,如果已有该键就更新他的值
                return Boolean(valueInCache);    //如果之前已有该键,则返回true
        

        值得注意的是, this.cache.set(key,{value, timeout})中的set也是Map对象中的方法,而不是类TimeLimitedCache中的set方法,在对象Map中,set 方法的作用是在 Map 中添加新的键值对或更新已有键对应的值。


        根据题目:get(key) :如果存在一个未过期的键,它应该返回这个键相关的值。否则返回 -1 。写出代码:

        get(key: number): number { return this.cache.get(key) ? this.cache.get(key).value : -1;
            }
        

        如果缓存中已经有这个键,则返回这个键所对应的值中的value属性(在前面定义的值MapEntry中有{value: number, timeout: NodeJS.Timeout}两个属性)


        最后根据题目count() :返回未过期键的总数,写出代码:

         count(): number { return this.cache.size;
            }
        

        方法二:时间戳

        type MapEntry = {value:number, expires:number}
        class TimeLimitedCache { cache = new Map();
            set(key: number, value: number, duration: number): boolean { const item = this.cache.get(key);
                this.cache.set(key,{value, expires: Date.now() + duration});
                if(item){ return item.expires >= Date.now();
                }
                return false;
            }
            
            get(key: number): number { const item = this.cache.get(key);
                if(!item){ return -1
                }
                if(item.expires >= Date.now()){ return item.value
                }else return -1;
            }
            
            count(): number { return [...this.cache.values()].filter(item => item.expires >= Date.now()).length
            }
        }
        

        解析

        set方法:

        set(key: number, value: number, duration: number): boolean { const item = this.cache.get(key);
                this.cache.set(key,{value, expires: Date.now() + duration});
                if(item){ return item.expires >= Date.now();
                }
                return false;
            }
        

        其中this.cache.set(key,{value, expires: Date.now() + duration});

        expires是缓存cache的过期时间,而过期时间由JavaScript的内置方法Date.now()获取一个时间戳。

        Date.now() 是 JavaScript 的一个内置方法,用于获取当前时间的时间戳,以毫秒为单位。这个方法返回自 1970 年 1 月 1 日 00:00:00 UTC(世界标准时间)至今的毫秒数。


        if(item){ return item.expires >= Date.now();
                }
        

        如果存在的item(注:get(key)返回的是key的缓存项,即键值对中的值),判断是否过期,没过期的话返回true,过期的话返回false。如果item在赋值的时候如果指定键不存在,则Map.get()方法会返回undefined,即item是undefined,也返回false。


        get方法:

        get(key: number): number { const item = this.cache.get(key);
                if(!item){ return -1
                }
                if(item.expires >= Date.now()){ return item.value
                }else return -1;
            }
        

        首先也给item赋值一个指定键的值,接着判断item是否有获取到对应的键的值,如果这个键不存在,则返回-1.接着判断这个键是否过期,如果未过期则返回item.value,否则也返回-1.


        count方法:

        count(): number { return [...this.cache.values()].filter(item => item.expires >= Date.now()).length
            }
        

        this.cache.values()返回的是迭代器对象,里面包含缓存的所有值。[…this.cache.values()] 这部分代码是使用展开语法 (…) 将 this.cache.values() 返回的迭代器中的值转换为一个数组。它会将缓存中所有的值提取出来,并以数组的形式展示出来。如:

        const cache = new Map();
        cache.set(1, { value: 100, expires: 1646945098183 });
        cache.set(2, { value: 200, expires: 1646945096183 });
        console.log([...this.cache.values()]);
        

        打印结果:

        [
          { value: 100, expires: 1646945098183 },
          { value: 200, expires: 1646945096183 }
        ]
        

        之后通过filter来过滤符合条件的item,过滤条件是item.expires >= Date.now(),最后加上.length,即count方法返回了未过期键的总数。