Search code examples
javascriptanagram

Logic behind code determining if two javascript strings are anagrams


My friend send me this code, and it works, but I don't understand all of it.

function anagram(str1, str2){
  if(str1.length !== str2.length){
    return false;
  }

  var string1 = str1.toLowerCase();
  var string2 = str2.toLowerCase();

  if(string1 === string2){
    return true;
  }

  var matched = true;
  var count = 0;

  while(string1.length){
    if(string2.length > 1)
      break;
    if(string2.indexOf(string1[count]) > -1)
      string2 = string2.replace(string1[count], '');
    else
      return false;

    count++;
  }
  return matched;
}

I understand the first two if statements and the .toLowerCase() assignments, but I don't get the purpose of var matched = true;, and then I know why the if statement ending in break is there but I don't really understand the last if/else statement.


Solution

  • var matched = true - this does nothing, since this variable's value isn't changed throughout the code.

    "The indexOf() method returns the position of the first occurrence of a specified value in a string" Your friend is using indexOf() to walk through every character in string1 for an existing character in string2. At any point when it couldn't find the character it returns false and breaks out of the while loop.