dataStorage.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. export class DataStorage {
  2. private static _InMemoryStorage: { [key: string]: boolean | number };
  3. public static ReadBoolean(key: string, defaultValue: boolean): boolean {
  4. try {
  5. if (this._InMemoryStorage && this._InMemoryStorage[key] !== undefined) {
  6. return this._InMemoryStorage[key] as boolean;
  7. } else if (typeof (Storage) !== "undefined" && localStorage.getItem(key) !== null) {
  8. return localStorage.getItem(key) === "true";
  9. } else {
  10. return defaultValue;
  11. }
  12. }
  13. catch (e) {
  14. this._InMemoryStorage = {};
  15. this._InMemoryStorage[key] = defaultValue;
  16. return defaultValue;
  17. }
  18. }
  19. public static StoreBoolean(key: string, value: boolean) {
  20. try {
  21. if (this._InMemoryStorage) {
  22. this._InMemoryStorage[key] = value;
  23. } else if (typeof (Storage) !== "undefined") {
  24. localStorage.setItem(key, value ? "true" : "false");
  25. }
  26. }
  27. catch (e) {
  28. this._InMemoryStorage = {};
  29. this._InMemoryStorage[key] = value;
  30. }
  31. }
  32. public static ReadNumber(key: string, defaultValue: number): number {
  33. try {
  34. if (this._InMemoryStorage && this._InMemoryStorage[key] !== undefined) {
  35. return this._InMemoryStorage[key] as number;
  36. } else if (typeof (Storage) !== "undefined" && localStorage.getItem(key) !== null) {
  37. return parseFloat(localStorage.getItem(key)!);
  38. } else {
  39. return defaultValue;
  40. }
  41. }
  42. catch (e) {
  43. this._InMemoryStorage = {};
  44. this._InMemoryStorage[key] = defaultValue;
  45. return defaultValue;
  46. }
  47. }
  48. public static StoreNumber(key: string, value: number) {
  49. try {
  50. if (this._InMemoryStorage) {
  51. this._InMemoryStorage[key] = value;
  52. } else if (typeof (Storage) !== "undefined") {
  53. localStorage.setItem(key, value.toString());
  54. }
  55. }
  56. catch (e) {
  57. this._InMemoryStorage = {};
  58. this._InMemoryStorage[key] = value;
  59. }
  60. }
  61. }