const STORAGE_KEY = 'NanoPowCache'
-let storage: { [key: string]: string } = {}
+let storage: Record<string, string> = {}
+
+function eq (a: unknown, b: bigint): boolean {
+ return typeof a === 'string'
+ && /^([a-f0-9]{2})+$/i.test(a)
+ && BigInt(`0x${a}`) === b
+}
function getItem (key: string): string | null {
if (globalThis?.localStorage) return globalThis.localStorage.getItem(key)
const item = getItem(STORAGE_KEY)
if (item == null) return null
const cache: WorkGenerateResponse[] = JSON.parse(item)
- for (const c of cache) {
- if (BigInt(`0x${c.hash}`) === hash && BigInt(`0x${c.difficulty}`) >= difficulty) {
- return c
- }
- }
- return null
+ const match = cache.find(c => eq(c.hash, hash) && eq(c.difficulty, difficulty))
+ return match ?? null
}
export function remove (hash: bigint): void {
if (item == null) return
const cache = JSON.parse(item) as WorkGenerateResponse[]
for (let i = 0; i < cache.length; i++) {
- if (BigInt(`0x${cache[i].hash}`) === hash) {
+ if (eq(cache[i].hash, hash)) {
cache.splice(i, 1)
}
}
- setItem('NanoPowCache', JSON.stringify(cache))
+ setItem(STORAGE_KEY, JSON.stringify(cache))
}
export function set (result: WorkGenerateResponse): WorkGenerateResponse {