Skip to content

Instantly share code, notes, and snippets.

@davalapar
Created November 3, 2019 02:01
Show Gist options
  • Save davalapar/b2d16dd16de45cbba178c710ee6abf04 to your computer and use it in GitHub Desktop.
Save davalapar/b2d16dd16de45cbba178c710ee6abf04 to your computer and use it in GitHub Desktop.
Candies
// does not use cookies
// uses localstorage instead
export default class Candies {
static set(key, value) {
if (typeof key !== 'string' || key === '') {
throw Error('Key must be a non-empty string');
}
localStorage.setItem(key, encodeURI(JSON.stringify(value)));
}
static get(key) {
if (typeof key !== 'string' || key === '') {
throw Error('Key must be a non-empty string');
}
const fetchedValue = localStorage.getItem(key);
if (fetchedValue === null || fetchedValue === 'null') {
return null;
}
if (fetchedValue === 'undefined') {
return undefined;
}
return JSON.parse(decodeURI(fetchedValue));
}
static has(key) {
if (typeof key !== 'string' || key === '') {
throw Error('Key must be a non-empty string');
}
return localStorage.getItem(key) !== null;
}
static remove(key) {
if (typeof key !== 'string' || key === '') {
throw Error('Key must be a non-empty string');
}
localStorage.removeItem(key);
}
static clear() {
localStorage.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment