Algorithm/LeetCode

[LeetCode] 2622. Cache With Time Limit

그랴 2023. 11. 13. 14:02

Promise and Time

 

문제

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.

 

key-value 쌍을 가져오고 설정하는 클래스를 작성하되, 각 key는 만료 기한과 연관되어 있습니다.

클래스는 3가지 public 메서드를 가지고 있습니다.

- set(key, value, duration) : 정수 key, 정수 value, 밀리초 단위의 duration을 받습니다. duration이 만료되면, key에 접근할 수 없습니다. 만료되지 않은 키가 존재한다면 true를 반환하고, 그렇지 않다면 false를 반환합니다. 이미 key가 존재하는 경우에는, value와 duration을 덮어씁니다.

- get(key) : 만료되지 않은 key가 있다면, 그 value를 리턴합니다. 없다면 -1을 리턴합니다.

- count() : 만료되지 않은 key들의 수를 리턴합니다.

 

 

 

 

var TimeLimitedCache = function() {
    this.cache = 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 found = this.cache.has(key)

    if(found) clearTimeout(this.cache.get(key).ref)

    this.cache.set(key, {
        value,
        ref: setTimeout(()=> this.cache.delete(key), duration)
    })

    return found
};

/** 
 * @param {number} key
 * @return {number} value associated with key
 */
TimeLimitedCache.prototype.get = function(key) {
    return this.cache.has(key) ? this.cache.get(key).value : -1
};

/** 
 * @return {number} count of non-expired keys
 */
TimeLimitedCache.prototype.count = function() {
    return this.cache.size
};

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

 

 

Map : 키-값 쌍을 저장하는 컬렉션 형태의 객체 (Object와 유사함)

- 키의 데이터 타입 제한이 없음

- Object와는 다르게 순서가 보장됨

 

 

위 코드를 클래스로 변환하면 아래와 같다.

class TimeLimitedCache {
    constructor() {
        this.cache = new Map();
    }

    set(key, value, duration) {
        let found = this.cache.has(key);

        if (found) clearTimeout(this.cache.get(key).ref);

        this.cache.set(key, {
            value,
            ref: setTimeout(() => this.cache.delete(key), duration)
        });

        return found;
    }

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

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