Skip to content

Instantly share code, notes, and snippets.

@mshwery
Last active August 29, 2015 14:00
Show Gist options
  • Save mshwery/11336760 to your computer and use it in GitHub Desktop.
Save mshwery/11336760 to your computer and use it in GitHub Desktop.
Wrapper to add optional TTL for localStorage.
// polyfill for localstorage into stale storage so this data store doesnt ever fail
if (!('localStorage' in window)) {
//if (!Modernizr.localstorage) {
window.localStorage = {
_data : {},
setItem : function(id, val) { return this._data[id] = String(val); },
getItem : function(id) { return this._data.hasOwnProperty(id) ? this._data[id] : undefined; },
removeItem : function(id) { return delete this._data[id]; },
clear : function() { return this._data = {}; }
};
}
// localstorage interface
// handles parsing JSON strings, etc
var DataStore = (function() {
// returns the value associated with the given key, if it exists
// returns null if the key doesn't exist
function getItem(name) {
var item = localStorage.getItem(name);
if (item) {
try {
item = JSON.parse(item);
} catch (err) {
console.warn(err);
}
}
return item;
}
// saves a new name/value pair if the key doesn't exist, otherwise
// updates the value
function setItem(name, value) {
try {
value = JSON.stringify(value);
} catch (err) {
console.warn(err);
}
return localStorage.setItem(name, value);
}
function set(name, value, ttl) {
if (ttl != null) ttl = +new Date() + ttl;
var item = {
value: value,
ttl: ttl
};
return setItem(name, item);
}
function get(name) {
var item = getItem(name);
// if there's a expired ttl, remove the item
if (item && item.ttl && item.ttl < +new Date()) {
return removeItem(name);
}
return item && item.value;
}
// remove an item from local storage
function removeItem(name) {
return localStorage.removeItem(name);
}
// delete all name/value pairs currently stored
function clear() {
return localStorage.clear();
}
return {
get: get,
set: set,
remove: removeItem,
clear: clear
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment