Last active
May 14, 2019 08:53
-
-
Save afterburn/67a3a5eab64757272bed6e9c16c7da40 to your computer and use it in GitHub Desktop.
LocalStorage helper class that automatically converts string values to their respective data types.
This file contains hidden or 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 { | |
static metadata = {} | |
static set (key, value) { | |
let storedValue = value | |
if (typeof value === 'object') { | |
storedValue = JSON.stringify(value) | |
} | |
if (!LocalStorage.metadata[key]) { | |
LocalStorage.metadata[key] = {} | |
} | |
LocalStorage.metadata[key].type = typeof value | |
window.localStorage.setItem(key, storedValue) | |
} | |
static get (key) { | |
const result = window.localStorage.getItem(key) | |
const metadata = LocalStorage.metadata[key] | |
switch (metadata.type) { | |
case 'object': { | |
return JSON.parse(result) | |
} | |
case 'number': { | |
return Number(result) | |
} | |
case 'boolean': { | |
return result === 'true' | |
} | |
default: { | |
return result | |
} | |
} | |
} | |
static exists (key) { | |
return !!window.localStorage.getItem(key) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment