Untitled

 avatar
unknown
plain_text
10 months ago
2.0 kB
7
Indexable
var TimeLimitedCache = function() {
    this.cache = {};
    this.cacheSize = 0;
    return null;
};

TimeLimitedCache.prototype.checkExpiry = function(key) {
    if (Object.keys(this.cache).length > 0) {
        console.log(this.cache);
        for (const key of Object.keys(this.cache)) {
            if (new Date().getTime() - this.cache[key].created > this.cache[key].expiry) {
                delete this.cache[key];
                if (this.cacheSize < 0) {
                    this.cacheSize = 0;
                }
                if (this.cacheSize > 0) {
                    this.cacheSize--;
                }
            }
        }
    }
}

/** 
 * @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) {
    this.checkExpiry();
    let out = false;
    if (this.cache[key] !== undefined) { out = true; this.cacheSize--; }
    this.cache[key] = {
        "value": value,
        "created": new Date().getTime(),
        "expiry": duration
    }
    this.cacheSize++;

    return out;
};

/** 
 * @param {number} key
 * @return {number} value associated with key
 */
TimeLimitedCache.prototype.get = function(key) {
    this.checkExpiry();
    if (Object.keys(this.cache).length > 0) {
        if (new Date().getTime() - this.cache[key].created > this.cache[key].expiry) {
            return -1;
        }
        return this.cache[key].value;
    } else {
        return -1;
    }
};

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

/**
 * const timeLimitedCache = new TimeLimitedCache()
 * timeLimitedCache.set(1, 42, 1000); // false
 * timeLimitedCache.get(1) // 42
 * timeLimitedCache.count() // 1
 */
Editor is loading...
Leave a Comment