Skip to content

Instantly share code, notes, and snippets.

@hamishhossack
Created July 27, 2015 14:35
Show Gist options
  • Save hamishhossack/448c797f4ac24ba512e2 to your computer and use it in GitHub Desktop.
Save hamishhossack/448c797f4ac24ba512e2 to your computer and use it in GitHub Desktop.
Local Storage Manager (timestamped, extra functionality, session & local storage) Deps: [underscore]
var CacheManager = window.CacheManager = function (storage) {
var name = '';
if (typeof storage !== "string") {
throw new TypeError('The name of storage needs to be a character string.');
}
name = _.capitalize(storage) + 'Storage';
if (!CacheManager[name]) {
throw new TypeError('The storage ' + name + ' is not defined.');
}
this.storage = CacheManager[name];
this.set = function (key, content, limit) {
var cacheTime = new Date(),
cacheContent = null;
if (typeof limit !== "number") {
if (limit === "hour") limit = 3600000;
else if (limit ==="day") limit = 86400000;
else if (limit === "week") limit = 604800000;
else limit = 604800000;
}
cacheTime.setTime(cacheTime.getTime() + limit);
cacheContent = JSON.stringify({
limit: cacheTime.getTime(),
content: content
});
this.storage.setItem(key, cacheContent);
};
this.get = function (key) {
var cache = null,
cacheContent = this.storage.getItem(key);
if (!cacheContent) {
return null;
}
cache = JSON.parse(cacheContent);
cache = _.defaults(cache, {
key: key,
storage: this
});
return new CacheManager.CacheContent(cache);
};
this.remove = function (key) {
this.storage.removeItem(key);
};
this.clear = function () {
this.storage.clear();
};
};
CacheManager.LocalStorage = window.localStorage;
CacheManager.SessionStorage = window.sessionStorage;
CacheManager.HashStorage = {
_store: {},
setItem: function (key, content) {
if (typeof key !== "string") {
throw new TypeError('The key needs to be a character string.');
}
if (!content) {
throw new TypeError('The contents which cash carries out are empty.');
}
this._store[key] = content;
},
getItem: function (key) {
if (!this._store[key]) {
return null;
}
return this._store[key];
},
removeItem: function (key) {
delete this._store[key];
},
clear: function () {
this._store = {};
}
};
CacheManager.CacheContent = function (properties) {
var instance = this, getter = null;
// generate getter methods
_.each(properties, function (value, key) {
getter = 'get' + _.capitalize(key);
instance[getter] = function () {
return properties[key];
};
});
_.defaults(instance, {
isLimit: function () {
return this.getLimit() > new Date().getTime();
},
destroy: function () {
var key = this.getKey(),
storage = this.getStorage();
storage.removeItem(key);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment