iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
Software Development

LeetCode-30 Days of JavaScript系列 第 17

LeetCode JS30-Day17 | 2622. Cache With Time Limit 有時間限制的緩存Cache

  • 分享至 

  • xImage
  •  

Day17 - 2622. Cache With Time Limit 有時間限制的緩存 Medium

Description❓

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()
    傳回未過期鍵的計數。

Points

Solution✍️

[ ▶️挑戰這一題 ][ 本日代碼 ]

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

//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}

上一篇
LeetCode JS30-Day16 | 2637. Promise Time Limit 有時間限制的Promise
下一篇
LeetCode JS30-Day18 | 2627. Debounce函數防抖
系列文
LeetCode-30 Days of JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言