Skip to content

Instantly share code, notes, and snippets.

@devsnek
Last active July 20, 2020 14:25
Show Gist options
  • Save devsnek/2dc7042dc28339f01c7a5fff5f4c17ad to your computer and use it in GitHub Desktop.
Save devsnek/2dc7042dc28339f01c7a5fff5f4c17ad to your computer and use it in GitHub Desktop.
// stolen from discord client
const ls = window.localStorage;
try {
delete window.localStorage;
} catch(o) {}
function localStorageTest() {
const test = 'test';
try {
ls.setItem(test, test);
ls.removeItem(test);
return true;
} catch (e) {
return false;
}
}
class LocalStorage {
get(key) {
let value = ls.getItem(key);
if (value !== null) {
try {
value = JSON.parse(value);
} catch (e) {}
}
return value;
}
has(key) {
return this.get(key) !== null;
}
set(key, value) {
ls.setItem(key, JSON.stringify(value));
}
remove(key) {
ls.removeItem(key);
}
clear() {
ls.clear();
}
}
class ObjectStorage {
constructor() {
this.storage = {};
}
get(key) {
return this.storage[key];
}
has(key) {
return this.get(key) !== null;
}
set(key, value) {
this.storage[key] = value;
}
remove(key) {
delete this.storage[key];
}
clear() {
this.storage = {};
}
}
const implementation = localStorageTest() ? new LocalStorage : new ObjectStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment