local_storage_manager.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. window.fakeStorage = {
  2. _data: {},
  3. setItem: function (id, val) {
  4. return this._data[id] = String(val);
  5. },
  6. getItem: function (id) {
  7. return this._data.hasOwnProperty(id) ? this._data[id] : undefined;
  8. },
  9. removeItem: function (id) {
  10. return delete this._data[id];
  11. },
  12. clear: function () {
  13. return this._data = {};
  14. }
  15. };
  16. function LocalStorageManager() {
  17. this.bestScoreKey = "bestScore";
  18. this.gameStateKey = "gameState";
  19. var supported = this.localStorageSupported();
  20. this.storage = supported ? window.localStorage : window.fakeStorage;
  21. }
  22. LocalStorageManager.prototype.localStorageSupported = function () {
  23. var testKey = "test";
  24. var storage = window.localStorage;
  25. try {
  26. storage.setItem(testKey, "1");
  27. storage.removeItem(testKey);
  28. return true;
  29. } catch (error) {
  30. return false;
  31. }
  32. };
  33. // Best score getters/setters
  34. LocalStorageManager.prototype.getBestScore = function () {
  35. return this.storage.getItem(this.bestScoreKey) || 0;
  36. };
  37. LocalStorageManager.prototype.setBestScore = function (score) {
  38. this.storage.setItem(this.bestScoreKey, score);
  39. };
  40. // Game state getters/setters and clearing
  41. LocalStorageManager.prototype.getGameState = function () {
  42. var stateJSON = this.storage.getItem(this.gameStateKey);
  43. return stateJSON ? JSON.parse(stateJSON) : null;
  44. };
  45. LocalStorageManager.prototype.setGameState = function (gameState) {
  46. this.storage.setItem(this.gameStateKey, JSON.stringify(gameState));
  47. };
  48. LocalStorageManager.prototype.clearGameState = function () {
  49. this.storage.removeItem(this.gameStateKey);
  50. };