Created
November 3, 2019 02:01
-
-
Save davalapar/b2d16dd16de45cbba178c710ee6abf04 to your computer and use it in GitHub Desktop.
Candies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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