Topic Description

Create a TimeLimitedCache class that allows you to get and set key-value pairs, with each key-value pair having an associated expiration time. Specifically, implement three methods:

// Example
Input:
actions = ["TimeLimitedCache", "set", "get", "count", "get"]
values = [[], [1, 42, 100], [1], [], [1]]
timeDelays = [0, 0, 50, 50, 150]

Output: [null, false, 42, 1, -1]

Explanation:
At t=0, create TimeLimitedCache.
At t=0, add (1: 42) with a duration of 100 milliseconds. Since the key 1 does not exist yet, return false.
At t=50, check key=1. Since it has not yet expired (100 milliseconds has not passed), return 42.
At t=50, call count(). There is currently one key (key=1), so return 1.
At t=100, key=1 expires.
At t=150, call get(1). Since the key has expired, return -1.

Answer

function TimeLimitedCache(){
	 this.cache = new Map()
}

TimeLimitedCache.prototype.set = function(key, value, duration) {
	const found = this.cache.has(key)
	if(found){
		clearTimeout(this.cache.get(key).timerId)
	}
	
	this.cache.set(key, {
    value,
    timerId: setTimeout(() => this.cache.delete(key), duration)
  })
  
  return found
}

TimeLimitedCache.prototype.get = function(key) {
    if(this.cache.has(key)) {
        return this.cache.get(key).value
    } else {
        return -1
    }
};

TimeLimitedCache.prototype.count = function() {
    return this.cache.size
};
class TimeLimitedCache {
    constructor() {
        this.cache = new Map()
    }

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

        if (found) {
            clearTimeout(this.cache.get(key).timerId)
        }

        this.cache.set(key, {
            value, value,
            timerId: 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
    }
}