Last active
December 17, 2015 23:59
-
-
Save DzikuVx/5693478 to your computer and use it in GitHub Desktop.
JavaScript Local Storage with item expire
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
/** | |
* localStorage with expire wrapper | |
*/ | |
var myStorage = (function() { | |
var self = {}; | |
/** | |
* Method unsets value in localStorage | |
*/ | |
self.unset = function(key) { | |
localStorage.removeItem(key); | |
}; | |
/** | |
* Method gets value from localStorage | |
* @param key | |
*/ | |
self.get = function(key) { | |
if (!localStorage[key]) { | |
return null; | |
} | |
var object = JSON.parse(localStorage[key]); | |
if (object.timestamp === null || new Date().getTime() < object.timestamp) { | |
return object.value; | |
} else { | |
return null; | |
} | |
}; | |
/** | |
* Method sets value in local storage | |
* | |
* @param key | |
* @param value | |
* @param expire in seconds | |
*/ | |
self.set = function(key, value, expire) { | |
var object; | |
if (!expire) { | |
object = { | |
value : value, | |
timestamp : null | |
}; | |
} else { | |
object = { | |
value : value, | |
timestamp : new Date().getTime() + (expire * 1000) | |
}; | |
} | |
localStorage[key] = JSON.stringify(object); | |
}; | |
return self; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment