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.
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.
Share Improve this question asked Jun 9, 2016 at 10:17 Cameron JonesCameron Jones 1412 silver badges15 bronze badges 4- simple for loop will do it – Callum Linington Commented Jun 9, 2016 at 10:20
-
You can loop through strings, so you set the
i = 0; i < 4; i++
so 4 is the amount of leading zeros you want to detect – Callum Linington Commented Jun 9, 2016 at 10:23 - w3schools./jsref/jsref_charat.asp - loop using it. Dunno if it will be more efficient, but its simple. – RaV Commented Jun 9, 2016 at 10:28
- or just if(str.substr(0, 4) == "0000") – RaV Commented Jun 9, 2016 at 10:31
2 Answers
Reset to default 5if (Number(n).toString() !== n){
console.log("leading 0 detected")
}
this may not be the fastest, but simpler than writing a function
function detect(hash, difficulty) {
for (var i = 0, b = hash.length; i < b; 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 parisons as well). This one should be quite fast.