const STORAGE_KEY = 'NanoPowCache'
-let storage: Record<string, string> = {}
+const storage = globalThis.localStorage ?? {
+ records: new Map<string, string>(),
+ 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'
&& 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))
}
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++) {
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
}