Skip to content

Instantly share code, notes, and snippets.

@MichaelFedora
Last active February 4, 2022 15:48
Show Gist options
  • Save MichaelFedora/031e1ec7a3df736b2b004d6b437e526e to your computer and use it in GitHub Desktop.
Save MichaelFedora/031e1ec7a3df736b2b004d6b437e526e to your computer and use it in GitHub Desktop.
Wrap a web storage with a prefix
/**
* Wrap a web storage with a prefix.
* @author Michael Fedora
* @link https://gist.github.com/MichaelFedora/031e1ec7a3df736b2b004d6b437e526e
*/
export class WrappedStorage implements Storage {
#store: Storage;
#prefix: string;
#key(k: string): string { return `${this.#prefix}_${k}`; }
#keys(): string[] {
const keys = new Set<string>();
for(let i = 0; i < this.#store.length; i++)
if(this.#store.key(i)?.startsWith(`${this.#prefix}_`))
keys.add(this.#store.key(i)!);
return Array.from(keys);
}
constructor(store: Storage, prefix: string) {
this.#store = store;
this.#prefix = prefix;
}
getItem(key: string): string | null {
return this.#store.getItem(this.#key(key));
}
setItem(key: string, value: string): void {
this.#store.setItem(this.#key(key), value);
}
removeItem(key: string): void {
this.#store.removeItem(this.#key(key));
}
clear(): void {
for(const key of this.#keys())
this.#store.removeItem(key);
}
key(i: number): string | null {
return this.#keys()[i]?.slice(this.#prefix.length + 1) ?? null;
}
get length(): number {
return this.#keys().length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment