Guest User

Untitled

a guest
Jan 23rd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. /*
  2. * Wrapper for html5 local storage
  3. */
  4. var Storage = function() {};
  5.  
  6. Storage.define = function(table) {
  7. window.localStorage[table] = window.localStorage[table] || "[]";
  8. return new Table(table);
  9. };
  10.  
  11. var Table = function(table, storage) {
  12. this.table = table;
  13. this.shortName = table.toLowerCase();
  14. };
  15.  
  16. Table.prototype.isNeedUpdate = function(data) {
  17. return this.diff(data).length > 0;
  18. };
  19.  
  20. Table.prototype.save = function(data) {
  21. var values = JSON.stringify(this.array(data));
  22. window.localStorage[this.table] = values;
  23. };
  24.  
  25. Table.prototype.load = function() {
  26. return JSON.parse(window.localStorage[this.table]);
  27. };
  28.  
  29. Table.prototype.diff = function(data) {
  30. var items = _.pluck(this.load(), "id");
  31. var ids = this.array(data);
  32. return _.difference(ids, items);
  33. };
  34.  
  35. Table.prototype.value = function(item) {
  36. return item[this.shortName];
  37. };
  38.  
  39. Table.prototype.array = function(items) {
  40. return _.reduce(items, function(memo, item) { return memo.concat(this.value(item)); }, [], this);
  41. };
  42.  
  43. Table.prototype.get = function(id) {
  44. var items = load();
  45. return _.detect(items, function(item) { item.id == id });
  46. };
  47.  
  48. window.Storage = Storage;
  49. window.Table = Table;
Add Comment
Please, Sign In to add comment