Skip to content

Instantly share code, notes, and snippets.

@rbndelrio
Created January 12, 2017 04:53
Show Gist options
  • Save rbndelrio/ac4ba19010832660dc4278a5d73da5c5 to your computer and use it in GitHub Desktop.
Save rbndelrio/ac4ba19010832660dc4278a5d73da5c5 to your computer and use it in GitHub Desktop.
import lz from 'lz-string'
function Lstorage() {
if (!(this instanceof Lstorage)) {
return new Lstorage();
}
Lstorage.a = {}
Lstorage.len = 0
return this
}
const cache = {}
let len = 0
const supportsLS = localStorage !== 'undefined'
const storage = supportsLS ? localStorage : {}
const get = (name) => {
if (supportsLS) {
return localStorage.getItem(name) || false
}
return cache[name] || false
}
const set = (...args) => {
let name
let data
if (args.length === 1) {
data = args[0]
} else {
name = args[0]
data = args[1]
}
const dataName = name || `ls_${Lstorage.len}`
if (supportsLS) {
storage.setItem(dataName, data)
} else {
storage[dataName] = data
}
if (cache[dataName] !== 'undefined') {
if (data === '') {
len -= 1
} else {
len += 1
}
Lstorage.len = len
}
cache[dataName] = data
return dataName
}
const rm = name => set(name, '')
const getLZ = (name) => {
let nameLZ
if (!name.contains('__lz')) {
nameLZ = name
} else {
nameLZ = `${name}__lz`
}
const dataLZ = get(nameLZ)
return lz.decompressFromUTF16(dataLZ)
}
const setLZ = (...args) => {
let name
let data
if (args.length === 1) {
data = args[0]
} else {
name = args[0]
data = args[1]
}
const dataLZ = lz.compressToUTF16(data)
const nameLZ = name ? `${name}__lz` : `ls_${Lstorage.len}__lz`
return set(nameLZ, dataLZ)
}
Lstorage.a = cache
Lstorage.len = len
Lstorage.prototype = {
get,
getLZ,
set,
setLZ,
rm,
}
const ls = new Lstorage()
export default { ls, Lstorage }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment