Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
whatevCache: a simple localStorage-if-you-got-it, otherwise not-at-all-persistent data object cache.
/*!
* JavaScript whatevCache - v0.2pre - 12/30/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// whatevCache.set( key, value [, ttl ] );
// (returns undefined on success, error object otherwise)
//
// whatevCache.get( key );
//
// whatevCache.remove( key );
var whatevCache = function(){
var global = this,
cache = {},
undef,
// "Borrowed" from Modernizr
use_localStorage = global.JSON && function(){
try {
return ( 'localStorage' in global ) && global.localStorage !== null;
} catch ( e ) {
return false;
}
}();
// Expose these methods.
return {
set: set,
get: get,
remove: remove
};
// Set a key-value pair with optional TTL.
function set( key, value, ttl ) {
var expires = ttl && new Date( +new Date() + ttl * 1000 ),
obj = {
expires: +expires,
value: value
};
if ( use_localStorage ) {
try {
localStorage[ key ] = JSON.stringify( obj );
} catch ( e ) {
return e;
}
} else {
cache[ key ] = obj;
}
}
// Get a value if it exists and hasn't expired.
function get( key ) {
var obj,
val;
if ( use_localStorage ) {
obj = localStorage[ key ];
if ( obj ) {
obj = JSON.parse( obj );
}
} else {
obj = cache[ key ];
}
if ( obj ) {
if ( obj.expires && obj.expires < +new Date() ) {
remove( key );
} else {
val = obj.value;
}
}
return val;
}
// Remove a key-value pair.
function remove( key ) {
if ( use_localStorage ) {
localStorage.removeItem( key );
} else {
delete cache[ key ];
}
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment