Skip to content

Instantly share code, notes, and snippets.

@davalapar
Created December 9, 2019 21:58
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 davalapar/9e4d3b56ecb82617c0a34438958fba99 to your computer and use it in GitHub Desktop.
Save davalapar/9e4d3b56ecb82617c0a34438958fba99 to your computer and use it in GitHub Desktop.
rocarstorage.js
export default class RocarStorage {
static set(key, value) {
if (typeof key !== 'string' || key === '') {
throw Error('RocarStorage 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('RocarStorage 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('RocarStorage error: Key must be a non-empty string');
}
return localStorage.getItem(key) !== null;
}
static remove(key) {
if (typeof key !== 'string' || key === '') {
throw Error('RocarStorage 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