4 ms·
I don't know why the author coded it this way, it can be done much simpler: function fuzzysearch(needle, haystack) { var hlen = haystack.length;
by nightcracker 11y ago
I don't know why the author coded it this way, it can be done much simpler:
function fuzzysearch(needle, haystack) {
var hlen = haystack.length;
var nlen = needle.length;
if (nlen > hlen) return false;
if (nlen === hlen) return needle === haystack;
for (var i = 0, j = 0; i < nlen; ++i, ++j) {
while (j < hlen && needle.charCodeAt(i) !== haystack.charCodeAt(j)) ++j;
if (j === hlen) return false;
}
return true;
}
- mraleph 11y agoIt's written with continue precisely to avoid additional `if (j === hlen)` check after the loop and having a single increment of `j` in the loop :) To be honest reasoning about the loop with continue is actually easier than about one without.
- joshstrange 11y agoHe says the algorithm was suggested by "Mr. Aleph, a crazy russian compiler engineer working at V8.". It's possible it was suggested to be written this way because V8 (and possibly other interpreters) can optimise it to be faster.