From a3f2579e11930394a3138058877b802fe3f8174b Mon Sep 17 00:00:00 2001 From: Ardis Lu Date: Sun, 19 Mar 2023 14:45:00 -0700 Subject: [PATCH] Use dedicated web worker for each calculation --- index.html | 40 +++++++--------------------------------- worker.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 33 deletions(-) create mode 100644 worker.js 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 }); +}); -- 2.47.3