Skip to content

Instantly share code, notes, and snippets.

@cvgellhorn
Created April 24, 2015 16:11
Show Gist options
  • Save cvgellhorn/2c36b7ab440b745d4ec6 to your computer and use it in GitHub Desktop.
Save cvgellhorn/2c36b7ab440b745d4ec6 to your computer and use it in GitHub Desktop.
JS localStorage handler (requirements: underscore.js)
/**
* Set and stringify local storage item(s)
*
* @param {(string|object)} key
* @param {*} value
*/
window.setStorage = function(key, value) {
if (_.isObject(key)) {
_.each(key, function(value, key) {
localStorage.setItem(key, JSON.stringify(value));
});
} else {
localStorage.setItem(key, JSON.stringify(value));
}
};
/**
* Get and parse local storage item
*
* @param {string} key
* @returns {*}
*/
window.getStorage = function(key) {
return JSON.parse(localStorage.getItem(key));
};
/**
* Remove local storage item(s)
*
* @param {(string|Array)} key
*/
window.removeStorage = function(key) {
if (_.isArray(key)) {
for (var i = 0, len = key.length; i < len; i++) {
localStorage.removeItem(key[i]);
}
} else {
localStorage.removeItem(key);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment