Mutations RegExp, why not always work?

Mutations RegExp, why not always work?
0.0 0

#1

My code works for each example, except the first one. Why is it happening? I used new RegExp, I know it’s probably not the best solution, but I came so far in this code, I don’t want to leave it almost ready.

Your code so far

function mutation(arr) {
  
var a = arr[0].toLowerCase();
var b = arr[1].toLowerCase().split('');

  for(var i=0;i<=b.length;i++){
      var c = new RegExp(b[i]);
      var x = c.test(a);
    if (x>0) {return true;}
  return false;
  }
  }

mutation(["hello", "hey"]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36 OPR/47.0.2631.55.

Link to the challenge:


#2

Your problem is your if statement. As it is your code only checks the first letter (which surprisingly is all you need to pass most of the tests). returning a value ends the function. Your code returns a value on the first iteration of the loop.

for(var i=0;i<=b.length;i++){
      var c = new RegExp(b[i]);
      var x = c.test(a);
    if (x>0) {return true;}  // should be something like if (!x){return false} instead
  return false;  // should be something like if i==b.length-1{return true} 
//as that means it got through the entire loop without returning false, so it must be true.
  }

Good luck!


#3

Your code never makes it past the first letter of the string in the first element of arr. Below I have add a few console.log statements so you can see the values of the variables as your code executes. You will need to view the console (Ctrl + Shft + I in Chrome) to see the results:

function mutation(arr) {
  
  var a = arr[0].toLowerCase();
  var b = arr[1].toLowerCase().split('');

  for(var i=0;i<=b.length;i++){
    var c = new RegExp(b[i]);
    console.log('a = ' + a);
    console.log('c = ' + c);
    var x = c.test(a);
    console.log('x = ' + x);
    console.log('x > 0 which is ' + x + ' > 0 evaluates to ' + (x > 0));
    if (x>0) {return true;}
    return false;
  }
}