DataCache - Simple storage wrapper

Allows JSON data to be persisted easily by user scripts

بۇ قوليازمىنى بىۋاسىتە قاچىلاشقا بولمايدۇ. بۇ باشقا قوليازمىلارنىڭ ئىشلىتىشى ئۈچۈن تەمىنلەنگەن ئامبار بولۇپ، ئىشلىتىش ئۈچۈن مېتا كۆرسەتمىسىگە قىستۇرىدىغان كود: // @require https://update.greatest.deepsurf.us/scripts/10443/56962/DataCache%20-%20Simple%20storage%20wrapper.js

  1. function DataCache(key) {
  2. this._key = key;
  3. this._data = {};
  4. this.load();
  5. }
  6. DataCache.prototype = {
  7. getValue: function(k) {
  8. return this._data[k];
  9. },
  10. setValue: function(k, v) {
  11. this._data[k] = v;
  12. this.save();
  13. },
  14. deleteValue: function(k) {
  15. if (k in this._data) {
  16. delete this._data[k];
  17. this.save();
  18. }
  19. },
  20. hasValue: function(k) {
  21. return k in this._data;
  22. },
  23. listValues: function() {
  24. return Object.keys(this._data).sort();
  25. },
  26. clear: function() {
  27. this._data = {};
  28. this.save();
  29. },
  30. save: function() {
  31. var s = JSON.stringify(this._data);
  32. GM_setValue(this._key, s);
  33. console.info('Cache(' + this._key + ') saved: ' + s);
  34. },
  35. load: function(s) {
  36. try {
  37. this._data = JSON.parse(s || GM_getValue(this._key));
  38. }
  39. catch (ex) {
  40. this.clear();
  41. }
  42. },
  43. edit: function() {
  44. var res = window.prompt('Edit cached package URLs', JSON.stringify(this._data, null, 2));
  45. if (res !== null) {
  46. try {
  47. this._data = res ? JSON.parse(res) : {};
  48. this.save();
  49. }
  50. catch (ex) {
  51. console.warn('Failed to update cache data: %s %o', ex.toString(), ex);
  52. }
  53. }
  54. },
  55. toString: function() {
  56. return 'Cache(' + this._key + '): [' + this.listValues.join('\n') + ']';
  57. },
  58. dump: function() {
  59. console.log('Cache(' + this._key + '):\n' + JSON.stringify(this._data, null, 2));
  60. }
  61. };