What is Nostr?
_kami_gawa / Su-do
npub1j44…he65
2025-02-04 18:01:40

_kami_gawa on Nostr: A funny challenge for devs, can you optimize this merkle root calculation? No chat ...

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);
```
Author Public Key
npub1j4442yrhl9dfnxe68gk6jefachmmmd6a4e4p4t0s7fvck997r6gqkghe65