Skip to content

Instantly share code, notes, and snippets.

@kn9ts
Created December 11, 2016 10:54
Show Gist options
  • Save kn9ts/b6839c6bea01288773319986bce104a2 to your computer and use it in GitHub Desktop.
Save kn9ts/b6839c6bea01288773319986bce104a2 to your computer and use it in GitHub Desktop.
/**
* LOCAL STORAGE MANAGEMENT FUNCTION
* @param options - local(bool), content(object), backup(bool)
* @param key
* STORE CONTENT locally or in cookie or BOTH
*
* HOW TO USE:
localStorage('key') // Returns the content if existing, or false if it doesnt
localStorage('key', {
content: the content, can be a raw object, string or raw array // it is stringified by the function
local: true/false // yes or no if you want to store only in localStorage
})
*/
var localStorage = function(key, options) {
if (options) { // store this data
if (!options.local) {
localStorage.setItem(key, JSON.stringify(options.content));
} else { // also in cookie too
if ($.cookie) $.cookie(key, options.content);
localStorage.setItem(key, JSON.stringify(options.content));
}
} else if (options === false) { // if options == false
localStorage.removeItem(key);
if ($.cookie) $.cookie(key, false); // remove everything
}
// if only one argument is given retrieve that data from localstorage
return arguments.length == 1 ? JSON.parse(localStorage.getItem(key)) : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment