Skip to content

Instantly share code, notes, and snippets.

@DzikuVx
Last active December 17, 2015 23:59
Show Gist options
  • Save DzikuVx/5693478 to your computer and use it in GitHub Desktop.
Save DzikuVx/5693478 to your computer and use it in GitHub Desktop.
JavaScript Local Storage with item expire
/**
* 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