Skip to content

Instantly share code, notes, and snippets.

@mminer
Created March 9, 2020 18:53
Show Gist options
  • Select an option

  • Save mminer/3b2460a96e71cfda75001d7a13068890 to your computer and use it in GitHub Desktop.

Select an option

Save mminer/3b2460a96e71cfda75001d7a13068890 to your computer and use it in GitHub Desktop.
Utility class to read and write arrays in localStorage / sessionStorage.
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