Cameron Jones Cameron Jones - 5 months ago 22
Node.js Question

Fastest way in JS to detect number of leading zeros

I am working on a project where I need to quickly check if there are a certain number of leading zeros in string. I have had success using regex:

var regex = new RegExp('^[0]{' + difficulty + '}.+');
if (regex.test(hash))


Also with substring and repeat:

if (hash.substring(0, difficulty) === '0'.repeat(difficulty))


For my specific purpose, speed is the most important element. I must find the fastest way to check if the number of leading zeros matches the difficulty. I have ran benchmark tests on both methods, but the results fluctuate in a way that I cannot tell which one is better. Also, if there is another better method, please let me know. Thanks in advance.

Answer
function detect(hash, difficulty) {
    var i;
    for (i = 0; i < hash.length; i++) {
        if (hash[i] != '0') {
            break;
        }
    }
    return i == difficulty;
}

Your methods have drawbacks that you construct intermediate objects and do heavy arithmetics (especially with regexp but with substring and full string comparisons as well). This one should be quite fast.