Skip to content

Instantly share code, notes, and snippets.

@jefsnare
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jefsnare/9539093 to your computer and use it in GitHub Desktop.
Save jefsnare/9539093 to your computer and use it in GitHub Desktop.
JG_LocalStorage helper methods for javascript localStorage
/**
* Various localStorage method helpers for setting,
* getting and checking localStorage data.
*/
JG_LocalStorage = (function () {
'use strict';
return {
/* add data to localStorage */
set: function (key, value) {
/* if the value is an object, stringify it to save it in localStorage */
if (typeof value === 'object') {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
/* retrieve data from localStorage object */
get: function (key) {
var data;
if (!this.hasData(key)) {
return false;
}
data = localStorage[key];
/* if the data is JSON, try to parse */
try {
return JSON.parse(data);
} catch (e) {
return data;
}
},
/* check if the item exists and it has data */
hasData: function (key) {
return !!localStorage[key] && !!localStorage[key].length;
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment