|
| 1 | +/** |
| 2 | + * 2622. Cache With Time Limit |
| 3 | + * https://leetcode.com/problems/cache-with-time-limit/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Write a class that allows getting and setting key-value pairs, however a time until |
| 7 | + * expiration is associated with each key. |
| 8 | + * |
| 9 | + * The class has three public methods: |
| 10 | + * - set(key, value, duration): accepts an integer key, an integer value, and a duration |
| 11 | + * in milliseconds. Once the duration has elapsed, the key should be inaccessible. |
| 12 | + * The method should return true if the same un-expired key already exists and false |
| 13 | + * otherwise. Both the value and duration should be overwritten if the key already exists. |
| 14 | + * |
| 15 | + * - get(key): if an un-expired key exists, it should return the associated value. |
| 16 | + * Otherwise it should return -1. |
| 17 | + * |
| 18 | + * - count(): returns the count of un-expired keys. |
| 19 | + */ |
| 20 | + |
| 21 | +var TimeLimitedCache = function() { |
| 22 | + this.cache = new Map(); |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {number} key |
| 27 | + * @param {number} value |
| 28 | + * @param {number} duration time until expiration in ms |
| 29 | + * @return {boolean} if un-expired key already existed |
| 30 | + */ |
| 31 | +TimeLimitedCache.prototype.set = function(key, value, duration) { |
| 32 | + const hit = this.cache.has(key) && this.cache.get(key)[1] > Date.now(); |
| 33 | + this.cache.set(key, [value, Date.now() + duration]); |
| 34 | + return hit; |
| 35 | +}; |
| 36 | + |
| 37 | +/** |
| 38 | + * @param {number} key |
| 39 | + * @return {number} value associated with key |
| 40 | + */ |
| 41 | +TimeLimitedCache.prototype.get = function(key) { |
| 42 | + if (!this.cache.has(key)) return -1; |
| 43 | + const [value, expiredAt] = this.cache.get(key); |
| 44 | + return expiredAt > Date.now() ? value : -1; |
| 45 | +}; |
| 46 | + |
| 47 | +/** |
| 48 | + * @return {number} count of non-expired keys |
| 49 | + */ |
| 50 | +TimeLimitedCache.prototype.count = function() { |
| 51 | + return [...this.cache.keys()].reduce((count, key) => { |
| 52 | + return this.cache.get(key)[1] > Date.now() ? ++count : count; |
| 53 | + }, 0); |
| 54 | +}; |
0 commit comments