How optimize my code?

function mutation(arr) {

let arr1 = arr[0].toLowerCase().split("");

let arr2 = arr[1].toLowerCase().split("");
let b;
for (let i = 0; i < arr2.length; i++){
  if (arr1.indexOf(arr2[i]) == -1){
    console.log("not found");
     b =  false;break;
  } else { console.log(" found");
  b = true;

}return b;

mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"]);

do you have questions about your code?

Yes How write the same function with fewer characters

optimising code means making it faster and more readable

speed is not an issue usually with this small algorithms - so, you should instead think how to make it more readable

for example, using more descriptive names for your variables


Thank you ):grinning:

Since we’re dealing with reasonably small texts we can make use of RegExp:

function mutation(arr) {
  const clean = [ Set(
  const seek = new RegExp(`[${clean}]`, 'gi')
  const found = arr[0].match(seek)

  return [ Set(found)].length === clean.length

What this code does is making use of RegExp’s character set selector [] which tells the engine to find any (or all if the global flag is present) and the case insensitive flag to match “i” with “I” for example since they’re basically the same letter.

I need to take the set to compare, lowercase it, split it into individual characters and get rid of the duplicates using the ES6 Set spread operator technique (for the length comparison to properly work).

All there is to do left is to return all the characters that match the character set and get rid of the duplicates with the aforementioned technique and properly return the comparison of lengths; if the lengths are equal it means that all the non-duplicated letters from the right are present in the left.

Notice that this is basically a Set Operation in general, you can represent it mathematically like this (read only if you mathy af):

A ∩ B = B

Where B is the set of characters to find. It means that the intersection (characters in common) of both sets (a set is a collection of unique elements in a potentially larger space) is equal to set B.

Now, part of the code you posted is similar to the “intersection” operation of two sets:

Set.prototype.difference = function(setB) {
    var difference = new Set(this);
    for (var elem of setB) {
    return difference;

There is no optimization issue with your code really, it all boils down to what operations you’re doing extra and I just can’t find anything wrong (assuming it works) so congrats :slight_smile:

Just for fun and giggles here’s another, semi-generic implementation

function mutation(arr) {
  const [haystack, needles] = [

  return needles.every(needle => haystack.includes(needle))

Thanks for your comment ):slightly_smiling_face:

I still have a lot to learn:slightly_smiling_face: