Skip to content

Instantly share code, notes, and snippets.

@simon-lang
Created February 6, 2018 00:45
Show Gist options
  • Save simon-lang/75dfbeee2fb7bc50686647995063c211 to your computer and use it in GitHub Desktop.
Save simon-lang/75dfbeee2fb7bc50686647995063c211 to your computer and use it in GitHub Desktop.
const version = require('../../../../version.txt').trim()
class LocalStorageService {
constructor(prefix, useVersion) {
if (useVersion) {
prefix = version + ':' + prefix
}
this.prefix = prefix
this.store = {}
this.withPrefix = function (key) {
if (this.prefix) {
key = this.prefix + '.' + key
}
return key
}
}
get(k) {
k = this.withPrefix(k)
try {
return JSON.parse(window.localStorage.getItem(k))
} catch (e) {
return this.store[k]
}
}
set(k, v) {
k = this.withPrefix(k)
try {
return window.localStorage.setItem(k, JSON.stringify(v))
} catch (e) {
this.store[k] = v
}
}
remove(k) {
k = this.withPrefix(k)
try {
return window.localStorage.removeItem(k)
} catch (e) {
delete this.store[k]
}
}
}
module.exports = LocalStorageService
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment