Skip to content

Instantly share code, notes, and snippets.

@wookiehangover
Created March 19, 2011 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wookiehangover/877067 to your computer and use it in GitHub Desktop.
Save wookiehangover/877067 to your computer and use it in GitHub Desktop.
a simple wrapper for localStorage
function cache(key, value, persist, expires){
if( typeof key == "undefined" ) return;
var data, is_json,
cache_value = localStorage.getItem(key);
// Return value if just the key is passed
if( typeof value == "undefined" ) {
// Detect if the string from localStorage tastes like JSON or an Array
is_json = /^\{|\[.+\}|\]$/.test(cache_value);
return ( is_json === true ) ? JSON.parse(cache_value): cache_value;
}
if( cache_value && persist ) {
// Stick new value into an array with old value(s)
data = JSON.parse( cache_value );
// Don't hold on to more than 5 objects in a key
if( data.length > 5 ) data.shift();
if( $.isArray(data) ) {
data.push(value);
} else {
data = [ data, value ];
}
} else {
data = value;
}
if( expires ) {
localStorage.setItem( key + "_expires", ( typeof expires == "number" ) ? expires: Date.now() );
}
localStorage.setItem( key, ( typeof value == "object" ) ? JSON.stringify(data): data );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment