Skip to content

Instantly share code, notes, and snippets.

@ali-master
Last active March 24, 2024 16:42
Show Gist options
  • Save ali-master/b36c1fb5e0673107d090cd8a2d6a1f1e to your computer and use it in GitHub Desktop.
Save ali-master/b36c1fb5e0673107d090cd8a2d6a1f1e to your computer and use it in GitHub Desktop.
LocalStorage Utils

localStorage Utils

Using

var pryStorage = new localStorageDB();

Set

pryStorage.set("test", "test value") // return boolean

Get

With key name, you can get value of key in localStorage db.

pryStorage.get("test") // return value

Get All

it's for get all records in localStorage and return Array<> of records.

pryStorage.getAll() // return Array<>

Remove

Remove Key in LocalStorage

pryStorage.remove("test") // return boolean

Clear All

Clear LocalStorage of Records.

pryStorage.clearAll() // return boolean

Check Browser Support

If your Browser does not support the localStorage, this function return false.

pryStorage.checkifSupport() // return boolean
// localStorage
var localStorageDB = function(){
this.key = this.key || 'unknown';
this.value = this.value || {};
}
// insert into localStorage
localStorageDB.prototype.set = function(key, value){
if(this.checkifSupport()){
try{
this.key = key;
this.value = value;
window.localStorage.setItem(this.key, this.value);
}catch(e){
throw new TypeError('Exceeded Storage Quota!');
return true;
}
}else{
throw new TypeError("No support. Use a fallback such as browser cookies or store on the server.");
return false;
}
}
localStorageDB.prototype.get = function(key){
try{
this.key = key;
var data = window.localStorage.getItem(this.key);
if(data && typeof(data) === 'object'){
return JSON.parse(data);
}else{
return data;
}
}catch(e){
return null;
}
}
localStorageDB.prototype.getAll = function(){
var array = new Array();
for(var i = 0; i < window.localStorage.length; i++){
var key = localStorage.key(i);
array.push(this.get(key));
};
return array;
}
localStorageDB.prototype.remove = function(key){
this.key = key;
try{
window.localStorage.removeItem(this.key);
if(window.localStorage.length == 0){
this.clearAll();
}
return true;
}catch(e){
return false;
}finally{
if(this.get(this.key)){
delete window.localStorage[this.key];
if(window.localStorage.length == 0){
this.clearAll();
}
}
}
}
localStorageDB.prototype.clearAll = function(){
try{
window.localStorage.clear();
return true;
}catch(e){
return false;
}
}
localStorageDB.prototype.checkifSupport = function(){
try{
return "localStorage" in window && window["localStorage"] !== null;
}catch(e){
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment