Guest User

Untitled

a guest
Nov 20th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. /**
  2. * Wrapper to add functionality to Web Storage API
  3. */
  4. class Storage {
  5. // We can use localStorage or sessionStorage with the same API
  6. constructor(name = "localStorage") {
  7. this.store = window[name];
  8. // Constant name of the entity array where we store all entity keys
  9. this.KEY_LIST_NAME = "KEYS";
  10. }
  11.  
  12. // Save on storage the item with the setItem API
  13. _saveItem(key, data) {
  14. const transformed = JSON.stringify(data);
  15. this.store.setItem(key, transformed);
  16. }
  17.  
  18. // Add key to the entity KEYS
  19. _addKeyToList(key) {
  20. const keyList = this.get(this.KEY_LIST_NAME) || [];
  21.  
  22. if (keyList.includes(key)) {
  23. return;
  24. }
  25.  
  26. this._saveItem(this.KEY_LIST_NAME, [...keyList, key]);
  27. }
  28.  
  29. // Remove key from the entity KEY_LIST_NAME
  30. _removeKeyToList(keyToRemove) {
  31. const keyList = this.get(this.KEY_LIST_NAME);
  32. const newList = keyList.filter(key => key !== keyToRemove);
  33. this._saveItem(this.KEY_LIST_NAME, newList);
  34. }
  35.  
  36. // Set data into entity with name key
  37. set(key, data) {
  38. this._saveItem(key, data);
  39. this._addKeyToList(key);
  40. }
  41.  
  42. // Get data from entity with name key
  43. get(key) {
  44. const data = this.store.getItem(key);
  45. return data ? JSON.parse(data) : undefined;
  46. }
  47.  
  48. // Remove entire entity from the store with name key
  49. remove(key) {
  50. this.store.removeItem(key);
  51. this._removeKeyToList(key);
  52. }
  53.  
  54. // Return the list of keys present in the store
  55. list() {
  56. return this.get(this.KEY_LIST_NAME);
  57. }
  58.  
  59. // Clean all the storage
  60. clear() {
  61. this.list().forEach(key => {
  62. if (this.exist(key)) {
  63. return this.remove(key);
  64. }
  65.  
  66. return this._removeKeyToList(key);
  67. });
  68. }
  69.  
  70. // Return boolean if exist the key in the storage
  71. exist(key) {
  72. const keyList = this.get(this.KEY_LIST_NAME);
  73. return keyList.includes(key);
  74. }
  75. }
Add Comment
Please, Sign In to add comment