Skip to content

Instantly share code, notes, and snippets.

@oivoodoo
Created August 25, 2011 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oivoodoo/1171026 to your computer and use it in GitHub Desktop.
Save oivoodoo/1171026 to your computer and use it in GitHub Desktop.
/*
* Wrapper for html5 local storage
*/
var Storage = function() {};
Storage.define = function(table) {
window.localStorage[table] = window.localStorage[table] || "[]";
return new Table(table);
};
var Table = function(table, storage) {
this.table = table;
this.shortName = table.toLowerCase();
};
Table.prototype.isNeedUpdate = function(data) {
return this.diff(data).length > 0;
};
Table.prototype.save = function(data) {
var values = JSON.stringify(this.array(data));
window.localStorage[this.table] = values;
};
Table.prototype.load = function() {
return JSON.parse(window.localStorage[this.table]);
};
Table.prototype.diff = function(data) {
var items = _.pluck(this.load(), "id");
var ids = this.array(data);
return _.difference(ids, items);
};
Table.prototype.value = function(item) {
return item[this.shortName];
};
Table.prototype.array = function(items) {
return _.reduce(items, function(memo, item) { return memo.concat(this.value(item)); }, [], this);
};
Table.prototype.get = function(id) {
var items = load();
return _.detect(items, function(item) { item.id == id });
};
window.Storage = Storage;
window.Table = Table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment