Skip to content

Instantly share code, notes, and snippets.

@townofdon
Created November 8, 2018 15:16
Show Gist options
  • Save townofdon/cc1cb18028a68f55754685f3ce9e979c to your computer and use it in GitHub Desktop.
Save townofdon/cc1cb18028a68f55754685f3ce9e979c to your computer and use it in GitHub Desktop.
Simple Application Store
/**
* A simple app store utilizing localStorage.
*/
/**
* Initialize the store.
*/
application = application || {};
application.store = {};
/**
* Update or create a stored setting.
*
* @param {string} key
* @param {string} value
* @returns {undefined}
*/
application.store.put = function(key, value) {
// both key and value must be non-null in order to set var in local storage
if (key && value) {
window.localStorage.setItem(key, value);
}
}
/**
* Update or create a stored setting. Converts value into JSON.
*
* @param {string} key
* @param {mixed} value
* @returns {undefined}
*/
application.store.putJson = function(key, value) {
// both key and value must be non-null in order to set var in local storage
if (key && value) {
application.store.put(key, JSON.stringify(value));
}
}
/**
* Get a stored setting.
*
* @param {string} key
* @returns {string}
*/
application.store.get = function(key) {
// if for some reason there is a var in local storage with NaN value, just return null instead
var item = window.localStorage.getItem(key);
if (
item === undefined ||
item === null ||
(!item && isNaN(item))
) {
return null;
}
return item;
}
/**
* Get a stored setting. Automatically parse JSON.
*
* @param {string} key
* @returns {string}
*/
application.store.getJson = function(key) {
// if for some reason there is a var in local storage with NaN value, just return null instead
var item = window.localStorage.getItem(key);
if (
item === undefined ||
item === null ||
(!item && isNaN(item))
) {
return null;
}
return JSON.parse(item);
}
/**
* Delete a stored setting.
*
* @param {string} key
* @returns {unknown}
*/
application.store.remove = function(key) {
return window.localStorage.removeItem(key);
}
/**
* Delete the entire store.
*
* @returns {undefined}
*/
application.store.clear = function() {
window.localStorage.clear();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment