一. 时间限制的缓存功能函数
思路
利用对象或者Map等数据结构将数据的加入时间和加入时传入的duration保存起来, 后面操作时根据它和当前时间进行比对来判断是否过期
解题方法
- 定义一个cache对象
- set函数: 中获取到当前时间,将其和duration一起保存到cache中
- get函数: 获取时从cache取chche中的数据,根据加入时的时间和duration进行判断是否已经过期
过期判断条件:获取时的时间 - 加入时的时间 > duration
- count函数:
定义一个cnt变量用以保存还没过期的数量,循环cache对象
调用get函数,将没有过期的进行累加到cnt上 返回cnt
实现
var TimeLimitedCache = function() {
this.cache = {};
};
const hasReflect = 'Reflect' in globalThis;
function getValue(target, key) {
if (!target) return target;
if (hasReflect) {
return key ? Reflect.get(target, key) : target;
}
return key ? target[key] : target;
}
function setValue(target, key, value) {
if (!target) return false;
if (hasReflect) {
Reflect.set(target, key, value);
return true;
}
target[key] = value;
return true;
}
function getKeys(target) {
if (hasReflect) {
return Reflect.ownKeys(target);
}
return Object.keys(target);
}
/**
* @param {number} key
* @param {number} value
* @param {number} time until expiration in ms
* @return {boolean} if un-expired key already existed
*/
TimeLimitedCache.prototype.set = function(key, value, duration) {
const now = Date.now();
const data = getValue(this.cache, key);
const { start = 0, value: val, duration: dur } = data || {};
let flag = false;
if (val && start && (now - start) <= dur) {
flag = true;
}
const _value = {
value,
start: now,
duration,
};
setValue(this.cache, key, _value);
return flag;
};
/**
* @param {number} key
* @return {number} value associated with key
*/
TimeLimitedCache.prototype.get = function(key) {
const now = Date.now();
const { start, duration, value } = getValue(this.cache, key) || {};
if (this.cache[key] && start && (now - start) <= duration) {
return value || -1;
}
delete this.cache[key];
return -1;
};
/**
* @return {number} count of non-expired keys
*/
TimeLimitedCache.prototype.count = function() {
let cnt = 0;
const keys = getKeys(this.cache);
for (let k of keys) {
cnt += this.get(k) === -1 ? 0 : 1;
}
return cnt;
};
/**
* Your TimeLimitedCache object will be instantiated and called as such:
* var obj = new TimeLimitedCache()
* obj.set(1, 42, 1000); // false
* obj.get(1) // 42
* obj.count() // 1
*/