Created
March 19, 2011 00:16
-
-
Save wookiehangover/877067 to your computer and use it in GitHub Desktop.
a simple wrapper for localStorage
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
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