JSFiddle - React, Tailwind, and code Playground

by sam_rat

HTML

<button data-process>Process</button>

<div>Status: <span data-status>Click Process</span></div>

CSS

div {
  margin-top: 15px;
}

JavaScript

function sha512(string) {
    return new Promise((resolve, reject) => {
        let buffer = (new TextEncoder).encode(string);

        crypto.subtle.digest('SHA-512', buffer.buffer).then(result => {
            resolve(Array.from(new Uint8Array(result)).map(
                c => c.toString(16).padStart(2, '0')
            ).join(''));
        }, reject);
    });
}

async function process(data, difficulty = 5) {
    let hash;
    let nonce = 0;
    
    do {
        hash = await sha512(data + nonce++);
    } while(hash.substr(0, difficulty) !== Array(difficulty + 1).join('0'));
    
    return hash;
}

const status = document.querySelector('[data-status]');
document.querySelector('[data-process]').addEventListener('click', () => {
	status.innerText = 'Calculating, please wait...'
  
  let timeStart = Date.now();
  let hash = process('somedata', 5).then(
  	hash => {
    	status.innerHTML = `Done in ${Date.now()-timeStart}ms<br />Result: ${hash}`;
		}, 
    err => status.innerText = 'An error occured'
  ); 
});