Last active
March 9, 2022 16:48
-
-
Save muke1908/0692ca007c0044f34ed0704bb60f60fd to your computer and use it in GitHub Desktop.
Use localstorage with faster read.
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
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