diff --git a/lscache.js b/lscache.js old mode 100644 new mode 100755 index ecd48f7..5dd229e --- a/lscache.js +++ b/lscache.js @@ -25,6 +25,9 @@ var lscache = function() { // Prefix for all lscache keys var CACHE_PREFIX = 'lscache-'; + // Default ttl if none specified + var DEFAULT_TIMEOUT = 60 * 1000 * 5 // 5 minutes + // Suffix for the key name on the expiration items in localStorage var CACHE_SUFFIX = '-cacheexpiration'; @@ -195,11 +198,15 @@ var lscache = function() { } // If a time is specified, store expiration info in localStorage - if (time) { + // If time is set to 0, make ttl forever (by not setting one) + // If time is not set, use DEFAULT_TIMEOUT + if (time && time != 0) { setItem(expirationKey(key), (currentTime() + time).toString(EXPIRY_RADIX)); - } else { + } else if (time === 0){ // In case they previously set a time, remove that info from localStorage. removeItem(expirationKey(key)); + } else { + setItem(expirationKey(key), (currentTime() + DEFAULT_TIMEOUT).toString(EXPIRY_RADIX)); } }, diff --git a/test.html b/test.html old mode 100644 new mode 100755 index 033f9ae..651b3b2 --- a/test.html +++ b/test.html @@ -53,8 +53,28 @@ value = {'name': 'Pamela', 'age': 26}; lscache.set(key, value, 3); equals(lscache.get(key).name, value.name, 'We expect name to be ' + value.name); + + +}); + +test('Testing set with default ttl and no ttl', function() { + + var CACHE_SUFFIX = '-cacheexpiration'; + + // no ttl, should use default + key = 'defaultttlkey'; + value = 7 + lscache.set(key, value) + ok(lscache.get(key+CACHE_SUFFIX), 'Key has a time to live value'); + + // 0 ttl, should not store a ttl (forever ttl) + key = 'foreverttlkey'; + value = 99 + lscache.set(key, value, 0) + equals(lscache.get(key+CACHE_SUFFIX), undefined, 'Key does not have a time to live'); }); + test('Testing remove()', function() { var key = 'thekey'; lscache.set(key, 'bla', 2);