I recently encountered this (admittedly) textbook JavaScript exercise and I'm having trouble conceptually walking through the two solutions I've been told are "best practices." I realize this is pretty basic stuff; I'm just trying to get as a solid grasp of the fundamentals here as I can.
The exercise itself is straightforward enough: write a function that checks to see if a string contains an identical number of two unique characters (in this case, 'x's and 'o's). The function must return a boolean and be case insensitive.
The first "best practice" solution, which I partially understood, was this:
function XO(string) {
let x = str.match(/x/gi);
let o = str.match(/o/gi);
return (x && x.length) === (o && o.length);
}
I understand the basic regex work being done in the first two lines of the function, but the precise role of the && logical operator in the third & final line of the function mystifies me. I'm having trouble, in plain English, explaining to myself (a) precisely what it does and (b) why something like return x === y alone is not a sufficiently robust solution in this case.
The second "best practice" solution I encountered was this:
const XO = str => {
str = str.toLowerCase().split('');
return str.filter(x => x === 'x').length === str.filter(x => x === 'o').length;
}
I'm afraid I have to admit most of this solution's logic escapes me, although I do grasp that .split('') is being run to produce an array of single characters that can be run through .filter.