FCC Bonfire Series 114: Mutations

Time for a new bonfire, mutations. This challenge will have us write a function that takes in an array with two items inside. Both of this items are strings.

The function should return true if the first string contains all of the letters present in the second string, ignoring capitalization. A few examples:

mutation(['House','houSE']); //-> true
mutation(['Strong','Trog']); //-> true
mutation(['Hello','hey']); //-> false
mutation(['Name','Names']); //-> false

To get this results, we should start by looping through the second string, and letter by letter, check if they are present in the first string. If every letter exists in the first array, return true. Otherwise, return false as soon as a letter does not exists in the first string.

For this task we are going to use the Array.prototype.indexOf() method. This array method can be applied to strings for a similar result. The indexOf method, takes an argument (in this case a letter) and returns the first position on the string it is called on that matches that one letter; if not found, it returns -1. For example:

var myString = 'Hello World';
myString.indexOf('y'); //-> -1
myString.indexOf('H'); //-> 0

Using this new method, let’s try to get this problem solved:

function mutation(array) {
  for (var i = 0; i < array[1].length; i++) {
    if (array[0].toLowerCase().indexOf(array[1][i].toLowerCase()) < 0) {
      return false;
    }
  }
  return true;
}

See what we did there? We first start looping through every item in the second string (array[1][i]) and then check if the result of the indexOf() method called on the first string (we call the toLowerCase method on both, first string and letter they are all lowercase characters) returns a number greater that 0 (this means that it exists within the string) with each of these letters. If any letter returns a negative number, immediatly return false, since we already found a letter that does not exists. Otherwise, return true at the end, since no letter returned a negative value.

As always, test your code, we don’t want it to explode. It can happen.