Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Created May 11, 2015 07:05
Show Gist options
  • Save HakurouKen/5b4b2cca4c5e7c7484a6 to your computer and use it in GitHub Desktop.
Save HakurouKen/5b4b2cca4c5e7c7484a6 to your computer and use it in GitHub Desktop.
A storage wrapper based on localStorage.
var Cache = (function(global){
var Cache = {};
var storage = global.localStorage;
Cache.isSupport = (function(){
return !!storage;
})();
Cache.set = function(key,val){
val = JSON.stringify(val);
if(val){
storage.setItem(key,val);
}
return val;
};
Cache.setAll = function(data){
var ret = {}
for (var key in data){
if( data.hasOwnProperty(key) ){
ret[key] = this.set(key,data[key]);
}
}
return ret;
};
Cache.get = function(key){
var val = storage.getItem(key);
try {
return JSON.parse(val);
} catch(e) {
return val || '';
}
};
Cache.getAll = function(){
var ret = {},
key;
for( var i = 0, l = storage.length; i < l; i++ ){
key = storage.key(i);
ret[key] = this.get(key);
}
return ret;
};
Cache.remove = function(key){
var val = this.get(key);
storage.removeItem(key);
return val;
};
Cache.clear = function(){
return storage.clear();
};
Cache.has = function(key){
return storage[key] === undefined && storage.hasOwnProperty(key);
};
Cache.len = function(){
return storage.length;
};
if(!Cache.isSupport){
for( var key in Cache ){
if( Cache.hasOwnProperty(key) && typeof Cache[key] === 'function' ){
Cache[key] = function(){};
}
}
}
return Cache;
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment