Skip to content

Instantly share code, notes, and snippets.

@zmilonas
Forked from ksafranski/SimpleStore.js
Last active May 8, 2018 14:43
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 zmilonas/0233d987a070875444e5fe97abe57c37 to your computer and use it in GitHub Desktop.
Save zmilonas/0233d987a070875444e5fe97abe57c37 to your computer and use it in GitHub Desktop.
Simple localStorage function with Cookie fallback for older browsers. ES6 syntax, so assuming transpiler for older browsers
/**
* Simple localStorage with Cookie Fallback
* v.1.0.0
*
* USAGE:
* ----------------------------------------
* Set New / Modify:
* store('my_key', 'some_value');
*
* Retrieve:
* store('my_key');
*
* Delete / Remove:
* store('my_key', null);
*/
const store = (key, value) => {
const lsSupport = !!localStorage;
if (typeof value !== "undefined" && value !== null) {
if ( typeof value === 'object' ) {
value = JSON.stringify(value);
}
return lsSupport ? localStorage.setItem(key, value) : createCookie(key, value, 30);
}
if (typeof value === "undefined") {
const data = lsSupport ? localStorage.getItem(key) : readCookie(key);
try {
const dataObj = JSON.parse(data);
return dataObj;
} catch(e) {
return data;
}
}
if (value === null) {
return lsSupport ? localStorage.removeItem(key) : createCookie(key, '', -1);
}
/**
* Creates new cookie or removes cookie with negative expiration
* @param key The key or identifier for the store
* @param value Contents of the store
* @param exp Expiration - creation defaults to 30 days
*/
const createCookie = (key, value, exp) => {
const expires = "; expires=" + (new Date(Date.now() + (exp * 24 * 60 * 60 * 1000))).toUTCString();
document.cookie = key + "=" + value + expires + "; path=/";
}
/**
* Returns contents of cookie
* @param key The key or identifier for the store
*/
const readCookie = (key) => (document.cookie.match('(^|; )'+key+'=([^;]*)')||0)[2];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment