Jason Knight
2 min readJun 19, 2020

Came back to this as I had a moment free... thinking on this (after finally understanding what it's trying to do) I agree the first step would be a string conversion, but I'd do it in-place.

Remember, unless it's an explicit Object parameters are passed as copies. As such you can re-use the existing "haystack" variable and simply do regex replacements on it.

To that end, I'd first regex replace out 0 and 1 to spaces (or any other character really), then regex out the vowels and consonants.

NORMALLY -- and I bet that as a quiz answer this was done to trip people up on purpose -- I'd say use .match(/010/g).length for the number of matches, but that only counts non-overlapping matches. Dimes to dollars that's what this test was "really" out to check for.

Hence you do have to brute force the count. I'd use a 'var in for' so as to reduce the code,

function binaryPatternMatching(needle, haystack) {
haystack = haystack.replace(
/[01]/g, ' '
).replace(
/[aeiouy]/gi, '0'
).replace(
/[bcdfghjklmnpqrstvwxz]/gi, '1'
);
for (
var
i = 0,
count = 0,
stop = haystack.length - needle.length;
i <= stop;
i++
) if (haystack.substr(i, needle.length) == needle) count++;
return count;
}

Though again this 'question' is the type of pointless pedanticry I'd expect from career educators and not something I would consider a proper test of one’s abilities... but like all such test questions they exist for people who know nothing about programming to gauge a programmer's skill.

Which is why they've been hot and trendy the past decade and a half, and really weren't a thing outside of "big iron" jobs prior to that.

Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse