Skip to content

Instantly share code, notes, and snippets.

@aitor
Forked from cowboy/ba-whatevcache.js
Created December 30, 2010 23:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aitor/760460 to your computer and use it in GitHub Desktop.
Save aitor/760460 to your computer and use it in GitHub Desktop.
/*!
* 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