Medium
Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.
The class has three public methods:
set(key, value, duration)
: accepts an integer key
, an integer value
, and a duration
in milliseconds. Once the duration
has elapsed, the key should be inaccessible. The method should return true
if the same un-expired key already exists and false
otherwise. Both the value and duration should be overwritten if the key already exists.get(key)
: if an un-expired key exists, it should return the associated value. Otherwise it should return -1
.count()
: returns the count of un-expired keys.宣告類別TimeLimitedCache
允許獲取get和設定set鍵值對,鍵值對中 每個鍵都個別關聯一個到期時間。
該類別有三個公開方法:
set(key,value,duration)
key
,整數value
和以毫秒為單位的duration
。duration
過後,該鍵即無法存取。true
,否則傳回 false
。value
和持續時間duration
都應被覆寫。get(key)
-1
。count()
class TimeLimitedCache {
//鍵值對中 每個鍵都個別關聯一個到期時間。
constructor() { this.cache = new Map(); }
//set(key,value,duration)
//key存在 回傳`true` 覆寫`value`和`duration`
//key不存在 回傳`false` 寫入`value`和`duration`
//cache寫入鍵值對 key需關聯過期時間,`duration`過後無法存取。
set(key, value, duration) {
let hasKey = this.cache.has(key);
if (hasKey) { clearTimeout(this.cache.get(key).timer); }
this.cache.set(key, {
value,
timer: setTimeout(() =>
this.cache.delete(key), duration
)
});
return hasKey;
}
get(key) { return this.cache.has(key) ? this.cache.get(key).value : -1; };
count() { return this.cache.size; };
}
//Testcase
let cache;
function runTest(cache, actions, timeDelays, testName) {
let result = [];
for (let i = 0; i < actions.length; i++) {
const returnValue = actions[i]();
result.push(returnValue);
}
console.log(`Output[${testName}]: [${result}]`);
}
//Test1
let actions = [
() => { cache = new TimeLimitedCache(); },
() => { return cache.set(1, 42, 100); },
() => { return cache.get(1); },
() => { return cache.count(); },
() => { return cache.get(1); }
];
let timeDelays = [0, 0, 50, 50, 150];
runTest(cache, actions, timeDelays, "Test1");
//Output[Test1]: [,false,42,1,42]
//Test2
actions = [
() => { cache = new TimeLimitedCache(); },
() => { return cache.set(1, 42, 50); },
() => { return cache.set(1, 50, 100); },
() => { return cache.get(1); },
() => { return cache.get(1); },
() => { return cache.get(1); },
() => { return cache.count(); }
];
timeDelays = [0, 0, 40, 50, 120, 200, 250];
runTest(cache, actions, timeDelays, "Test2");
//Output[Test2]: [,false,true,50,50,50,1]
const TimeLimitedCache =
🔑key -> 🔐{value,timer:duration}