Last active
February 4, 2022 15:48
-
-
Save MichaelFedora/031e1ec7a3df736b2b004d6b437e526e to your computer and use it in GitHub Desktop.
Wrap a web storage with a prefix
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
/** | |
* 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