This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
135. localStorage with expiration
class myLocalStorage { static setItem(key, value, ttl = null) { const now = Date.now(); const item = {value: value, expiration: ttl ? now + ttl : null}; localStorage.setItem(key, JSON.stringify(item)); } static getItem(key) { const item = JSON.parse(localStorage.getItem(key)); if (!item) { return null; } if (item.expiration && Date.now() > item.expiration) { localStorage.removeItem(key); return null; } return item.value; }}
Explanation:
setItem
method accepts three parameters - key, value and ttl (time-to-live) which is optional and defaults to null.- It creates an object
item
withvalue
as the value parameter andexpiration
calculated based on the ttl parameter. If ttl is null, expiration is set to null. item
object is then stored in localStorage with key as provided key parameter.getItem
method accepts one parameter - key.- It retrieves the item from localStorage with provided key and parses it into
item
object. - If item is null, it returns null.
- If item has expiration and it has passed, it removes the item from localStorage and returns null.
- Otherwise, it returns the value of the item.