Hard
This question is a daily question and will count towards your daily streak.
You're building a caching system for an e-commerce platform that needs to store product data but automatically expire old entries. What will be the output of the following code when run?
1class ExpiringCache {2 constructor(defaultTTL = 3600000) { // 1 hour in milliseconds3 this.cache = new Map();4 this.timeouts = new Map();5 this.defaultTTL = defaultTTL;6 }78 set(key, value, ttl = this.defaultTTL) {9 const expiryTime = Date.now() + ttl;1011 if (this.timeouts.has(key)) {12 clearTimeout(this.timeouts.get(key));13 }1415 const timeoutId = setTimeout(() => {16 this.delete(key);17 }, ttl);1819 this.cache.set(key, {20 value,21 expiryTime22 });23 this.timeouts.set(key, timeoutId);2425 return this;26 }2728 get(key) {29 const item = this.cache.get(key);30 if (!item) return undefined;3132 if (Date.now() > item.expiryTime) {33 this.delete(key);34 return undefined;35 }3637 return item.value;38 }3940 delete(key) {41 clearTimeout(this.timeouts.get(key));42 this.timeouts.delete(key);43 this.cache.delete(key);44 }45}4647const cache = new ExpiringCache(2000); // 2 seconds TTL48cache.set('product1', { name: 'Laptop', price: 999 });49cache.set('product2', { name: 'Phone', price: 699 }, 1000); // 1 second TTL5051setTimeout(() => {52 console.log('After 1.5 seconds:');53 console.log('Product1:', cache.get('product1'));54 console.log('Product2:', cache.get('product2'));55}, 1500);