-
-
Save rwaldron/760403 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* 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