61224574f83f20585a07424b4c0924a9bcfd899c7e26ba45c7115f7f1e43601b28ad5c0902e1a4e63b6cc80488d942d8ab5754b592d7b619fb913a4f5c3176 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Copyright (c) 2013 ESHA Research
  3. * Dual licensed under the MIT and GPL licenses:
  4. * http://www.opensource.org/licenses/mit-license.php
  5. * http://www.gnu.org/licenses/gpl.html
  6. *
  7. * Allows use of a number as 'overwrite' param on set calls to give time in seconds after
  8. * which the value should not be retrievable again (an expiration time).
  9. *
  10. * Status: BETA - useful, needs testing
  11. */
  12. ;(function(_) {
  13. var prefix = 'exp@',
  14. suffix = ';',
  15. parse = _.parse,
  16. _get = _.get,
  17. _set = _.set;
  18. _.parse = function(s, fn) {
  19. if (s && s.indexOf(prefix) === 0) {
  20. s = s.substring(s.indexOf(suffix)+1);
  21. }
  22. return parse(s, fn);
  23. };
  24. _.expires = function(s) {
  25. if (s && s.indexOf(prefix) === 0) {
  26. return parseInt(s.substring(prefix.length, s.indexOf(suffix)), 10);
  27. }
  28. return false;
  29. };
  30. _.when = function(sec) {// if sec, return sec->date, else date->sec
  31. var now = Math.floor((new Date().getTime())/1000);
  32. return sec ? new Date((now+sec)*1000) : now;
  33. };
  34. _.cache = function(area, key) {
  35. var s = _get(area, key),
  36. sec = _.expires(s);
  37. if (sec && _.when() >= sec) {
  38. return area.removeItem(key);
  39. }
  40. return s;
  41. };
  42. _.get = function(area, key) {
  43. var s = _.cache(area, key);
  44. return s === undefined ? null : s;
  45. };
  46. _.set = function(area, key, string, sec) {
  47. try {
  48. if (sec) {
  49. string = prefix + (_.when()+sec) + suffix + string;
  50. }
  51. _set(area, key, string);
  52. } catch (e) {
  53. if (e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
  54. var changed = false;
  55. for (var i=0,m=area.length; i<m; i++) {
  56. if (_.cache(area, key) === undefined) {
  57. changed = true;
  58. }
  59. }
  60. if (changed) {
  61. return _.set.apply(this, arguments);
  62. }
  63. }
  64. throw e;
  65. }
  66. };
  67. })(window.store._, undefined);