Created
March 9, 2020 18:53
-
-
Save mminer/3b2460a96e71cfda75001d7a13068890 to your computer and use it in GitHub Desktop.
Utility class to read and write arrays in localStorage / sessionStorage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class StorageArray { | |
| private storage: Storage; | |
| constructor(storage: Storage) { | |
| this.storage = storage; | |
| } | |
| get(key: string): string[] | null { | |
| const jsonString = this.storage.getItem(key); | |
| if (!jsonString) { | |
| return null; | |
| } | |
| return JSON.parse(jsonString); | |
| } | |
| set(key: string, items: string[]) { | |
| const jsonString = JSON.stringify(items); | |
| this.storage.setItem(key, jsonString); | |
| } | |
| addItem(key: string, item: string) { | |
| const items = this.get(key) ?? []; | |
| items.push(item); | |
| this.set(key, items); | |
| } | |
| removeItem(key: string, item: string) { | |
| const items = this.get(key); | |
| if (!items) { | |
| return; | |
| } | |
| const index = items.indexOf(item); | |
| if (index < 0) { | |
| return; | |
| } | |
| items.splice(index, 1); | |
| this.set(key, items); | |
| } | |
| } | |
| export const localStorageArray = new StorageArray(localStorage); | |
| export const sessionStorageArray = new StorageArray(sessionStorage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment