Last active
March 10, 2024 19:41
-
-
Save john-doherty/28e4a711380a186893723c988c54eb29 to your computer and use it in GitHub Desktop.
localStorage helper (takes care of casting types)
This file contains 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
/** | |
* local storage helper (takes care of casting types) | |
*/ | |
var localStorageHelper = { | |
/** | |
* Check if item exists in local storage. | |
* @param {string} key - variable name | |
* @return {boolean} true if key exists, otherwise false | |
*/ | |
exists: function (key) { | |
return Object.prototype.hasOwnProperty.call(localStorage, key); | |
}, | |
/** | |
* Get an item from local storage | |
* @param {string} key - variable name | |
* @return {any} correctly cast value if it exists | |
*/ | |
get: function (key) { | |
// always get value as a string | |
var value = String(localStorage.getItem(key)); | |
if (value === 'null') return null; | |
if (value === 'undefined') return undefined; | |
// if it's a float | |
if (/^[0-9.]+$/.test(value)) return parseFloat(value); | |
// if it's an integer | |
if (/^[-0-9]+$/.test(value)) return parseInt(value, 10); | |
// if it's a boolean | |
if (value === 'true' || value === 'false') return (value === 'true'); | |
// if it's a JSON object | |
if (value[0] === '{' || value[0] === '[') { | |
try { | |
var parsed = JSON.parse(value); | |
if (typeof parsed === 'object' || Array.isArray(parsed)) { | |
return parsed; | |
} | |
} catch (e) { | |
// Not a JSON object or array | |
} | |
} | |
return value; | |
}, | |
/** | |
* Save an item to local storage | |
* @param {string} key - variable name | |
* @param {any} value - value of variable to save | |
* @return {void} | |
*/ | |
set: function (key, value) { | |
if (typeof key !== 'string') { | |
throw new TypeError('localStorage: Key must be a string'); | |
} | |
if (typeof value === 'object' || Array.isArray(value)) { | |
value = JSON.stringify(value); | |
} | |
localStorage.setItem(key, value); | |
}, | |
/** | |
* Remove an item from local storage | |
* @param {string} key - variable name | |
* @return {void} | |
*/ | |
remove: function (key) { | |
localStorage.removeItem(key); | |
}, | |
/** | |
* Clear all local storage values | |
* @return {void} | |
*/ | |
clear: function () { | |
localStorage.clear(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment