From: Chris Duncan Date: Wed, 27 May 2026 07:32:45 +0000 (-0700) Subject: Simplify local storage polyfill. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=9f29c98c00af5d6cc5971b53791fbb6d37807091;p=nano-pow.git Simplify local storage polyfill. --- diff --git a/src/utils/cache.ts b/src/utils/cache.ts index f40ddb9..022ee21 100644 --- a/src/utils/cache.ts +++ b/src/utils/cache.ts @@ -5,7 +5,18 @@ import { WorkGenerateResponse } from 'nano-pow' const STORAGE_KEY = 'NanoPowCache' -let storage: Record = {} +const storage = globalThis.localStorage ?? { + records: new Map(), + getItem (key: string): string | null { + return this.records.get(key) + }, + removeItem (key: string): void { + this.records.delete(key) + }, + setItem (key: string, item: string): void { + this.storage.set(key, item) + } +} function eq (a: unknown, b: bigint): boolean { return typeof a === 'string' @@ -13,27 +24,12 @@ function eq (a: unknown, b: bigint): boolean { && BigInt(`0x${a}`) === b } -function getItem (key: string): string | null { - if (globalThis?.localStorage) return globalThis.localStorage.getItem(key) - return storage[key] -} - -function removeItem (key: string): void { - if (globalThis?.localStorage) return globalThis.localStorage.removeItem(key) - storage = {} -} - -function setItem (key: string, item: string): void { - if (globalThis?.localStorage) return globalThis.localStorage.setItem(key, item) - storage[key] = item -} - function clear (): void { - removeItem(STORAGE_KEY) + storage.removeItem(STORAGE_KEY) } function get (hash: bigint, difficulty: bigint): WorkGenerateResponse | null { - const item = getItem(STORAGE_KEY) + const item = storage.getItem(STORAGE_KEY) if (item == null) return null const cache: WorkGenerateResponse[] = JSON.parse(item) const match = cache.find(c => eq(c.hash, hash) && eq(c.difficulty, difficulty)) @@ -41,7 +37,7 @@ function get (hash: bigint, difficulty: bigint): WorkGenerateResponse | null { } function remove (hash: bigint): void { - const item = getItem(STORAGE_KEY) + const item = storage.getItem(STORAGE_KEY) if (item == null) return const cache = JSON.parse(item) as WorkGenerateResponse[] for (let i = 0; i < cache.length; i++) { @@ -49,14 +45,14 @@ function remove (hash: bigint): void { cache.splice(i, 1) } } - setItem(STORAGE_KEY, JSON.stringify(cache)) + storage.setItem(STORAGE_KEY, JSON.stringify(cache)) } function set (result: WorkGenerateResponse): WorkGenerateResponse { - const item = getItem(STORAGE_KEY) ?? '[]' + const item = storage.getItem(STORAGE_KEY) ?? '[]' const cache: WorkGenerateResponse[] = JSON.parse(item) if (cache.push(result) > 1000) cache.shift() - setItem(STORAGE_KEY, JSON.stringify(cache)) + storage.setItem(STORAGE_KEY, JSON.stringify(cache)) return result }