2

So I have this freeCodeCamp project for building a Tic-Tac-Toe game with JavaScript. One of the function in the code is written as follows:

function searchRegex(list, who) {
    var whoRegex = who === 1 ? player1.regex : player2.regex;
    return list.findIndex(function(c) {
        return whoRegex.test(c) && c.split('').indexOf('-') > -1;
    });
}

If, for instance, player1 chooses 'X', the CPU will use 'O', and the regex in each players' object is:

player1.regex = /(X-X|XX)/g
player2.regex = /(O-O|OO)/g

Every single time the computer is about to make a move, firstly it evaluates if it's about to win (so it puts its mark and wins). If all rows, cols and crosses return -1 from the searchRegex function, it looks for the case it is about to lose (so it puts its mark and avoids losing). If this second condition is not true, so the player is not about to win, it runs other code to decide its next move.

The problem is: some times the computer is about to win, but the function returns -1, so the code understands that it is not.

One of the cases it occurs is when I have an array of rows like this:

rows = ["O-O","XO-","X-X"];

The first check, code calls searchRegex(rows,0), so it checks the rows list for player2.regex matches.

It looks to me that when the searchRegex function evaluates that arrow, rows[0] should be a match, but instead it returns -1. I wonder why...

Can anyone see what I'm missing?

P.S.: When the code reads the rows, cols and crosses, it puts a hyphen when the spot is blank.

Rahul
  • 2,658
  • 12
  • 28

0 Answers0