Last active
July 9, 2023 08:33
-
-
Save Arifursdev/9da07df86fbaafa4c60992f324f8046e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Stores a value in the localStorage with an optional expiration time. | |
* | |
* @param {string} key - The key to associate with the stored value. | |
* @param {*} value - The value to be stored. | |
* @param {number} expiration - The duration in milliseconds for which the item should be stored before it expires. | |
*/ | |
function setItemWithExpiration(key, value, expiration) { | |
const item = { | |
value: value, | |
expiration: expiration ? new Date().getTime() + expiration : null | |
}; | |
localStorage.setItem(key, JSON.stringify(item)); | |
} | |
// setItemWithExpiration('example', 'abcd', 60 * 60 * 1000) // 1hr | |
/** | |
* Retrieves a value from the localStorage based on the provided key. It also checks if the stored item has expired and removes it if necessary. | |
* | |
* @param {string} key - The key associated with the stored value. | |
* @returns {*} - The stored value if it exists and has not expired, otherwise returns null. | |
*/ | |
function getItemWithExpiration(key) { | |
const item = JSON.parse(localStorage.getItem(key)); | |
if (item && item.expiration && new Date().getTime() > item.expiration) { | |
localStorage.removeItem(key); | |
return null; | |
} | |
return item ? item.value : null; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment