Skip to content

Instantly share code, notes, and snippets.

@muke1908
Last active March 9, 2022 16:48
Show Gist options
  • Save muke1908/0692ca007c0044f34ed0704bb60f60fd to your computer and use it in GitHub Desktop.
Save muke1908/0692ca007c0044f34ed0704bb60f60fd to your computer and use it in GitHub Desktop.
Use localstorage with faster read.
class LocalStorage {
private cache: Record<string, any> = {};
static instance: any;
constructor() {
if (!!LocalStorage.instance) {
return LocalStorage.instance;
}
LocalStorage.instance = this;
this.hydratedCache();
return this;
}
get(key: string) {
if (this.cache[key]) {
return this.cache[key];
}
const inLS = localStorage.getItem(key);
if (inLS) {
return JSON.parse(inLS);
}
return null;
}
set(key: string, value: Record<string, any> | string | number) {
this.cache[key] = value;
localStorage.setItem(key, JSON.stringify(value));
}
remove(key: string) {
delete this.cache[key];
localStorage.removeItem(key);
}
private hydratedCache() {
try {
const cache = {};
const keys = Object.keys(localStorage);
for (let i in keys) {
const key = keys[i];
this.cache[key] = JSON.parse(localStorage[key])
}
}catch(err) {
console.log('failed to hydratedCache', err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment