/** * @description Get the number of key-value pairs currently stored in local storage. */ export const getLengthOfLocalStorage = (): number => { return localStorage.length } /** * @description Get an array of all keys currently stored in local storage. */ export const getAllKeysFromLocalStorage = (): string[] => { const keys: string[] = [] for (let i = 0; i < localStorage.length; i = i + 1) { const key = localStorage.key(i) if (key !== null) { keys.push(key) } } return keys } /** * @description Check if a specific key exists in local storage. */ export const hasKeyInLocalStorage = (key: string): boolean => { return localStorage.getItem(key) !== null } /** * @description Retrieve a value from local storage by its key. */ export const getFromLocalStorage = (key: string): string | null => { return localStorage.getItem(key) } /** * @description Set a value in local storage by its key. * If the value is null, the key will be removed from local storage. */ export const setToLocalStorage = (key: string, value: string | null): string | null => { if (value !== null) { localStorage.setItem(key, value) } else { localStorage.removeItem(key) } return value } /** * @description Remove a value from local storage by its key. * Returns the removed value, or null if the key did not exist. */ export const removeFromLocalStorage = (key: string): string | null => { const value = localStorage.getItem(key) localStorage.removeItem(key) return value } /** * @description Clear all key-value pairs from local storage. */ export const clearLocalStorage = (): void => { localStorage.clear() } /** * @description Subscribe to changes in local storage. The callback will be * invoked whenever any key-value pair in local storage changes. * Returns a function to unsubscribe from the changes. */ export const subscribeAllChangesOfLocalStorage = ( subscriber: (event: StorageEvent) => void, ): (() => void) => { const internalSubscriber = (event: StorageEvent): void => { subscriber(event) } const subscribe = (): void => { window.addEventListener("storage", internalSubscriber) } const unsubscribe = (): void => { window.removeEventListener("storage", internalSubscriber) } subscribe() return unsubscribe } /** * @description Subscribe to changes in a specific key in local storage. * The callback will be invoked whenever the value of the key changes. * Returns a function to unsubscribe from the changes. */ export const subscribeKeyChangesOfLocalStorage = ( key: string, subscriber: (event: StorageEvent) => void, ): (() => void) => { const internalSubscriber = (event: StorageEvent): void => { if (event.key === key) { subscriber(event) } } const subscribe = (): void => { window.addEventListener("storage", internalSubscriber) } const unsubscribe = (): void => { window.removeEventListener("storage", internalSubscriber) } subscribe() return unsubscribe }