UNPKG

opnet

Version:

The perfect library for building Bitcoin-based applications.

46 lines (45 loc) 1.57 kB
import { BaseThreader } from './SharedThreader.js'; import { jsonWorkerScript } from './worker-scripts/JSONWorker.js'; export class JsonThreader extends BaseThreader { workerScript = jsonWorkerScript; threadingThreshold; constructor(options = {}) { super(options); this.threadingThreshold = options.threadingThreshold ?? 16_384; } async parse(json) { if (json.length < this.threadingThreshold) { return JSON.parse(json); } const result = await this.run('parse', json); return result; } async parseBuffer(buffer) { if (buffer.byteLength <= this.threadingThreshold) { const text = new TextDecoder().decode(buffer); return JSON.parse(text); } const result = await this.runWithTransfer('parse', buffer, [buffer]); return result; } async stringify(data) { const result = JSON.stringify(data); if (result.length < this.threadingThreshold) { return result; } return (await this.run('stringify', data)); } async fetch(request) { const result = await this.run('fetch', request); return result; } } const GLOBAL_KEY = Symbol.for('opnet.jsonThreader'); const globalObj = (typeof globalThis !== 'undefined' ? globalThis : global); if (!(GLOBAL_KEY in globalObj)) { globalObj[GLOBAL_KEY] = new JsonThreader(); } export function initJsonThreader() { return Promise.resolve(globalObj[GLOBAL_KEY]); } export const jsonThreader = globalObj[GLOBAL_KEY];