Skip to content

Instantly share code, notes, and snippets.

@azjezz
Last active May 7, 2020 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save azjezz/e7e49dd317fea6f7a2a9f4ab54af2124 to your computer and use it in GitHub Desktop.
Save azjezz/e7e49dd317fea6f7a2a9f4ab54af2124 to your computer and use it in GitHub Desktop.
simple storage class for javascript - test included
class Storage {
static get(key) {
let value = localStorage.getItem(key);
return value === null ? null : JSON.parse(value);
}
static set(key,value) {
return localStorage.setItem(key,JSON.stringify(value));
}
static unset(key) {
if(this.isset(key))
return localStorage.removeItem(key);
else
return null;
}
static clear() {
return localStorage.clear();
}
static isset(key) {
return this.get(key) !== null;
}
}
let a = {
"a": 15,
"t": 12
};
let b = 5;
let c = 'Hello';
let d = true;
let e = [5,5,8,9];
Storage.set('object',a);
Storage.set('int',b);
Storage.set('string',c);
Storage.set('boolean',d);
Storage.set('array',e);
console.log('Getting object :');
console.log(Storage.get('object'));
console.log('Getting int : ');
console.log(Storage.get('int'));
console.log('Getting string : ');
console.log(Storage.get('string'));
console.log('Getting boolean :');
console.log(Storage.get('boolean'));
console.log('Getting array : ');
console.log(Storage.get('array'));
console.log('settings cat to tom.');
Storage.set('cat','tom');
console.log('checking if cat is set ( expecting true ) :');
console.log(Storage.isset('cat'));
console.log('unset cat.');
Storage.unset('cat');
console.log('checking if cat is set ( expecting false ) :');
console.log(Storage.isset('cat'));
console.log('settings a to b');
Storage.set('a','b');
console.log('settings b to c');
Storage.set('b','c');
console.log('checking if a & b are set ( expecting true - true ) :');
console.log(Storage.isset('a'));
console.log(Storage.isset('b'));
console.log('cleaning storage');
Storage.clear();
console.log('checking if a & b are set ( expecting false - false ) :');
console.log(Storage.isset('a'));
console.log(Storage.isset('b'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment