Exercise 18: Storage with TTL and Auto Cleanup

Problem Statement

Function `setWithTTL(key, value, ttl)` banao jo TTL ke saath store kare aur auto cleanup kare. Example: setWithTTL("temp", "data", 60000) → auto removes after 1 minute

Sample Output:

setWithTTL("temp", "data", 60000)
// Auto removes after 1 minute

Solution

const setWithTTL = (key, value, ttl) => {
  localStorage.setItem(key, JSON.stringify({value, expiry: Date.now() + ttl}));
  setTimeout(() => localStorage.removeItem(key), ttl);
};

Explanation

Overall Goal:

  • TTL ke saath store karna with auto cleanup.

Real world:

  • Temporary data: auto cleanup.
  • Cache: TTL-based expiration.