Serafim

Untitled

Mar 5th, 2015
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.   window.LocalStorage = (function() {
  3.     var time;
  4.  
  5.     LocalStorage.prototype.prefix = 'cache.';
  6.  
  7.     LocalStorage.prototype.cache = 60;
  8.  
  9.     function LocalStorage() {
  10.       this.prefix = 'cache.';
  11.       this.cache = 60;
  12.     }
  13.  
  14.     LocalStorage.prototype.remember = function(name, minutes, callback) {
  15.       var result;
  16.       if (callback == null) {
  17.         callback = (function() {});
  18.       }
  19.       if (this.has(name)) {
  20.         return this.read(name).value;
  21.       }
  22.       result = callback((function(_this) {
  23.         return function(result) {
  24.           if (result != null) {
  25.             return _this.write(name, result, minutes);
  26.           }
  27.         };
  28.       })(this));
  29.       if (result != null) {
  30.         this.write(name, result, minutes);
  31.       }
  32.       return this;
  33.     };
  34.  
  35.     LocalStorage.prototype.put = function(name, value, minutes) {
  36.       if (minutes == null) {
  37.         minutes = this.cache;
  38.       }
  39.       this.write(name, value, minutes);
  40.       return this;
  41.     };
  42.  
  43.     LocalStorage.prototype.has = function(name) {
  44.       var result;
  45.       result = this.read(name);
  46.       if (result == null) {
  47.         return false;
  48.       }
  49.       return result.timestamp > time();
  50.     };
  51.  
  52.     LocalStorage.prototype.read = function(name) {
  53.       var result;
  54.       result = localStorage.getItem(this.prefix + name);
  55.       if (result != null) {
  56.         return JSON.parse(result);
  57.       } else {
  58.         return void 0;
  59.       }
  60.     };
  61.  
  62.     LocalStorage.prototype.write = function(name, val, minutes) {
  63.       if (minutes == null) {
  64.         minutes = this.cache;
  65.       }
  66.       localStorage.setItem(this.prefix + name, JSON.stringify({
  67.         value: val,
  68.         timestamp: time() + minutes
  69.       }));
  70.       return this;
  71.     };
  72.  
  73.     time = function() {
  74.       return Math.ceil((new Date).getTime() / 1000 / 60);
  75.     };
  76.  
  77.     return LocalStorage;
  78.  
  79.   })();
  80.  
  81. }).call(this);
Advertisement
Add Comment
Please, Sign In to add comment