A funny challenge for devs, can you optimize this merkle root calculation?

No chat gpt lol

```

const { createHash } = require('crypto');

const sha = (v) => createHash('sha256').update(v).digest('hex');

const computeMerkleRoot = (txs) => {

let i = 0;

let next = [];

while (true) {

if (i >= txs.length) {

txs = next;

next = [];

i = 0;

} else {

if (!!txs[i + 1]) {

next.push(sha(txs[i] + txs[i + 1]));

} else {

next.push(sha(txs[i] + txs[i]));

}

i += 2;

}

if (!txs.length || txs.length == 1) {

break;

}

}

console.log('Merkle root:', txs.join(''));

};

const txs = ['A', 'B', 'C', 'D'];

computeMerkleRoot(txs);

```

Reply to this note

Please Login to reply.

Discussion

No replies yet.