Basic Algorithm Scripting: Mutations strange behaviour

Basic Algorithm Scripting: Mutations strange behaviour
0

#1

I do not understand why is this code working perfectly in the console but not on the text editor provided by FCC.

function mutation(arr) {
  str1 = arr[0].toLowerCase().split("").sort();
  str2 = arr[1].toLowerCase().split("").sort();
  if(str2.length > str1.length) {
    return false;
  }
  for(let i = 0; i < str2.length; i++) {
    if(str2[i] != str1[i])
      return false;
  }
  return true;
}

It says str1 is not defined.


#2

Nevermind, I was forgetting let.


#3

Hello,
Something intrigued me in your code: you’re returning “false” if str2.length > str1.length,
what happens if str2 is larger than str1, yet contains the same characters ?
example:

mutation(["Mary", "Aarmy"]);

Your function would return “false”, not the expected result.
Have you thought of managing duplicate characters ?


#4

Yeah, I got it, thanks for your concern though.

function mutation(arr) {
  let str1 = arr[0].toLowerCase().split("");
  let str2 = arr[1].toLowerCase().split("");
  for(let i = 0; i < str2.length; i++) {
    if(str1.indexOf(str2[i]) == -1)
      return false;
  }
  return true;
}