From: Ardis Lu Date: Sun, 19 Mar 2023 21:45:00 +0000 (-0700) Subject: Use dedicated web worker for each calculation X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=a3f2579e11930394a3138058877b802fe3f8174b;p=4-byte-gen Use dedicated web worker for each calculation --- diff --git a/index.html b/index.html index 4543ac5..d0effca 100644 --- a/index.html +++ b/index.html @@ -57,10 +57,6 @@ diff --git a/worker.js b/worker.js new file mode 100644 index 0000000..c864ade --- /dev/null +++ b/worker.js @@ -0,0 +1,36 @@ +// From noble-hashes v1.3.0 +import { keccak256 } from '/keccak256.js'; +const encoder = new TextEncoder(); + +function validate(functionName, minimum) { + const byteArray = keccak256(encoder.encode(functionName)).slice(0, 4); + for (let i = 0; i < minimum; i++) { + if (byteArray[i] === 0) { + if (i + 1 === minimum) { + const hash = `0x${[...byteArray].map(b => b.toString(16).padStart(2, '0')).join('')}`; + return hash; + } + } + else { + return false; + } + } +} + +function calculateOptimizedName(name, parametersTypes, minimum) { + let counter = 0n; + let functionName = `${name}_${counter}(${parametersTypes})`; + let hash = validate(functionName, minimum); + while (!hash) { + counter++; + functionName = `${name}_${counter.toString(36)}(${parametersTypes})`; + hash = validate(functionName, minimum); + } + return { functionName, hash }; +} + +addEventListener('message', e => { + const { name, parametersTypes, minimum } = e.data; + const { functionName, hash } = calculateOptimizedName(name, parametersTypes, minimum); + postMessage({ functionName, hash }); +});