Skip to content

Instantly share code, notes, and snippets.

@Maher4Ever
Created June 12, 2011 18:45
Show Gist options
  • Save Maher4Ever/1021872 to your computer and use it in GitHub Desktop.
Save Maher4Ever/1021872 to your computer and use it in GitHub Desktop.
Adam Roderick's version of CacheProvider with better packaging! http://jsperf.com/maher-cacheprovider
(function (window, undefined) {
/**
* {Boolean} useLocalStorageIfAvailable - optional, defaults to true. The CacheProvider object will
* use the HTML5 localStorage object, if available
*/
var CacheProvider = (function() {
var _hasLocalStorage,
_useLocalStorage,
_cache = [],
CacheProviderOperations;
try {
_hasLocalStorage = (window.localStorage) && window.localStorage !== null;
} catch (ex) {
_hasLocalStorage = false;
}
if (_hasLocalStorage) {
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function(key) {
return JSON.parse(this.getItem(key));
};
}
CacheProviderOperations = {
/**
* {String} k - the key
*/
get: function(k) {
if (_useLocalStorage && _hasLocalStorage) {
var isObject = localStorage.getItem(k + '___isObject');
var action = isObject ? 'getObject' : 'getItem';
return localStorage[action](k) || undefined;
} else {
return _cache[k] || undefined;
}
},
/**
* {String} k - the key
* {Object} v - any kind of value you want to store
*/
set: function(k, v) {
if (_useLocalStorage && _hasLocalStorage) {
if (typeof v !== 'string') {
// make assumption if it's not a string, then we're storing an object
localStorage.setObject(k, v);
localStorage.setItem(k + '___isObject', true);
} else {
try {
localStorage.setItem(k, v);
} catch (ex) {
if (ex.name == 'QUOTA_EXCEEDED_ERR') {
// developer needs to figure out what to start invalidating
throw new Exception(v);
}
}
}
} else {
// put in our local object
_cache[k] = v;
}
// return our newly cached item
return v;
},
/**
* {String} k - the key
* {Boolean} local - put this in local storage
*/
clear: function(k) {
if (_useLocalStorage && _hasLocalStorage) {
localStorage.removeItem(k);
localStorage.removeItem(k + '___isObject');
}
// delete in both caches - doesn't hurt.
delete _cache[k];
}
};
return function (useLocalStorageIfAvailable) {
_useLocalStorage = 'undefined' == typeof(useLocalStorageIfAvailable) ? true : useLocalStorageIfAvailable;
return CacheProviderOperations;
};
})();
window.CacheProvider = CacheProvider;
})(this);
/*
Usage
------------------------------
var cache = new CacheProvider();
cache.set('maher', 'Maher Salam');
document.write('<p>' + cache.get('maher') + '</p>');
cache.clear('maher');
document.write('<p>' + cache.get('maher') + '</p>');
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment