Exercise 7: Get Storage Value with Expiry Check
Problem Statement
Function `getWithExpiry(key)` banao jo value get kare aur expired ho to null return kare.
Example: getWithExpiry("token") => value or null if expired
Sample Output:
getWithExpiry("token") => "abc123" (if not expired)
getWithExpiry("token") => null (if expired)Solution
const getWithExpiry = (key) => {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
if (Date.now() > item.expiry) {
localStorage.removeItem(key);
return null;
}
return item.value;
};Explanation
Overall Goal:
- Expired values ko handle karna.
Real world:
- Token validation: expiry checks.
- Cache: expired data removal.