Skip to main content

2622. Cache With Time Limit

https://leetcode.com/problems/cache-with-time-limit/

Javascript

var TimeLimitedCache = function() {
this.cache = {}
};

/**
* @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 cache = this.cache
const isExist = cache.hasOwnProperty(key)

if (isExist) {
clearTimeout(cache[key]['timer'])
}

const timer = setTimeout(() => {
delete cache[key]
}, duration)

cache[key] = {
timer: timer,
value: value
}
return isExist
};

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

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

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

Typescript

type LimitedCacheType = {
timer: ReturnType<typeof setTimeout>;
value: number;
};

class TimeLimitedCache {
cache: {[key: number]: LimitedCacheType}

constructor() {
this.cache = {}
}

set(key: number, value: number, duration: number): boolean {
const cache = this.cache
const isExist = cache.hasOwnProperty(key)

if (isExist) {
clearTimeout(cache[key]['timer'])
}

const timer = setTimeout(() => {
delete cache[key]
}, duration)

cache[key] = {
timer: timer,
value: value
}

return isExist
}

get(key: number): number {
return this.cache.hasOwnProperty(key) ? this.cache[key]['value'] : -1
}

count(): number {
return Object.keys(this.cache).length
}
}