Skip to content

Instantly share code, notes, and snippets.

@aaronsnoswell
Created December 6, 2011 07:31
Show Gist options
  • Save aaronsnoswell/1437203 to your computer and use it in GitHub Desktop.
Save aaronsnoswell/1437203 to your computer and use it in GitHub Desktop.
Easy localStorage caching
/**
* Stores the given key, value pair in localStorage, if it is available
*/
function setLocalStorageValue(key, value) {
if (window.localStorage) {
try {
localStorage.setItem(key, value);
} catch (e) {
// For some reason we couldn't save the value :(
console.log("ERROR | Unable to save to localStorage!", key, value, e);
}
}
}
/**
* Gets a value from localStorage
* Returns the default if localStorage is unavailable, or there is no
* stored value for that key
*/
function getLocalStorageValue(key, def) {
if (window.localStorage) {
var value = localStorage.getItem(key);
if((value == null) || (value == "undefined")) {
/* We had a bit of trouble reading the value assumedly
* Regardless, try save the value for next time
*/
setLocalStorageValue(key, def);
value = def;
}
// Try to (intelligently) cast the item to a number, if applicable
if(!isNaN(value*1)) value = value*1;
return value;
}
// If localStorage isn't available, return the default
return def;
}
/**
* Clears the given key's value from localStorgage
*/
function clearLocalStorageValue(key) {
if (window.localStorage) {
try {
localStorage.removeItem(key);
} catch (e) {
// For some reason we couldn't clear the value :S
console.log("ERROR | Unable to clear localStorage value!", key, e);
}
}
}
@aaronsnoswell
Copy link
Author

Added Number casting to getLocalStorageValue

@aaronsnoswell
Copy link
Author

Fixed typo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment