Last active
May 30, 2017 14:17
-
-
Save abramovantonru/1c90f2d651fd6a30b5304f5dd2a371bf to your computer and use it in GitHub Desktop.
javascript (pure) logic for localStorage of browser
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
window.SimpleStorage = (function () { | |
const storageName = 'tmpName'; | |
return{ | |
get: function (id) { | |
var storage = localStorage.getItem(storageName); | |
if(storage)try { | |
storage = JSON.parse(storage); | |
return typeof storage[id] !== 'undefined' ? storage[id] : null; | |
} catch (e) { | |
return null; | |
} | |
return null; | |
}, | |
getAll: function () { | |
var storage = localStorage.getItem(storageName); | |
if(storage)try { | |
storage = JSON.parse(storage); | |
return storage; | |
} catch (e) { | |
return null; | |
} | |
return null; | |
}, | |
set: function (id, data) { | |
var storage = ConstructorStorage.check(); | |
storage[id] = data; | |
localStorage.setItem(storageName, JSON.stringify(storage)); | |
}, | |
remove: function (id) { | |
var storage = ConstructorStorage.check(); | |
delete storage[id]; | |
localStorage.setItem(storageName, JSON.stringify(storage)); | |
}, | |
removeAll: function () { | |
localStorage.removeItem(storageName); | |
}, | |
check: function () { | |
var storage = localStorage.getItem(storageName); | |
if(storage)try { | |
storage = JSON.parse(storage); | |
return $.isEmptyObject(storage) ? ConstructorStorage.create() : storage; | |
} catch (e) { | |
return ConstructorStorage.create(); | |
} else | |
return ConstructorStorage.create(); | |
}, | |
create: function () { | |
var storage = {}; | |
localStorage.setItem(storageName, JSON.stringify(storage)); | |
return storage; | |
} | |
} | |
})(); | |
SimpleStorage.check(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment