Is there a better way to do mutation?

Is there a better way of doing mutation:

my code so far


function mutation(arr) {
arr[0] = arr[0].toLowerCase();
arr[1] = arr[1].toLowerCase();

for(let i = 0; i < arr[1].length; i++) {
  if(arr[0].indexOf(arr[1].charAt(i)) == -1) {
    return false;
  }
}
return true;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36.

Challenge: Mutations

Link to the challenge:

“Better” is subjective. Your code is clean and readable.

You could certainly make it shorter, in fact you can write the whole function with just one line, but “shorter” isn’t always “better”. Is this more readable than your solution?

function mutation(arr) {
  return arr[1].toLowerCase()
     .split('')
     .every(letter => arr[0].toLowerCase().split('').indexOf(letter) !== -1)
}
2 Likes

I agree with @jsdisco. The “better” is subjective. You can find many different ways to solve the same problem.

Here is my solution with ES6 syntax:

function mutation(arr) {
  const set = new Set();
  const [first, second] = arr;
  const toFormat = (s) => s.toLowerCase();

  [...first].forEach(c => set.add(toFormat(c)));

  for(let c of second) {
    if(!set.has(toFormat(c))) return false
  }

  return true;
}

You probably won’t often see the Sets in the code, but it is good to know that this thing exists. If you don’t understand the code, I will be glad to explain but give yourself a try to figure it for yourself first.

1 Like