Skip to content

Instantly share code, notes, and snippets.

@afterburn
Last active May 14, 2019 08:53
Show Gist options
  • Save afterburn/67a3a5eab64757272bed6e9c16c7da40 to your computer and use it in GitHub Desktop.
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.
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