-2

I'm doing a basic algorithm scripting challenge on FCC and I want to return true if a string in a first element of an array contains all of the letters of the string in the second element of the array, or false otherwise.

I've written some code for this. However I can't seem to pass one test:

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

I've tried removing the global flag and have tried using constructor notation and literal notation based on recommendations from the FCC community, but to no avail.

This is the code:

function mutation(arr) {
  let patt = new RegExp("[arr.1]", "i");
  return patt.test(arr[0]);

}

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

The function is supposed to return true instead it returns false. What is wrong with my code?

Biffen
  • 6,249
  • 6
  • 28
  • 36
raeign
  • 9
  • 4

1 Answers1

0

new RegExp("[arr.1]", "i") uses [arr.1] (literally) as the regular expression, which is why it doesn't work.

I wouldn't use a regular expression for this, it's simpler to do it directly. For instance:

function mutation(arr) {
  const lc = arr[0].toLowerCase();
  return [...arr[1].toLowerCase()].every(ch => lc.includes(ch));
}

...or to make searching the string not be a linear search:

function mutation(arr) {
  const chars = new Set([...arr[0].toLowerCase()]);
  return [...arr[1].toLowerCase()].every(ch => chars.has(ch));
}

...but if you have to use regex, you could generate an array with all the permutations of arr[1] (["Hello", "oHell", "loHel", ...]) (perhaps using the answers here) then create your regular expression using beginning/ending anchors (^, $) and alternations (|) of all the permutations:

let permutations = /*...use the linked answers to create permutations...*/;
let patt = new RegExp("^(?:" + permutations.join("|") + ")$", "i");

If arr[1] may contain characters that are special in regular expressions, you'll need to escape them (perhaps using one of the answers here):

let patt = new RegExp("^(?:" + permutations.map(escapeRegExp).join("|") + ")$", "i");

(Again: There is no built-in escapeRegExp, see the answers to the question linked above for how to create one.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for pointing that out. (For some reason FCC lets it pass most of the tests, which is why I didnt catch that error). But when I used your code, it passes the test even if it only matches with one letter. I want it to match all the letters. – raeign Aug 06 '19 at 08:46
  • @raeign - Doh! Of course it does. :-) (The RegExp version. The others are right.) I wouldn't use RegExp for this, I'd use one of the other solutions. But hmmmm..... – T.J. Crowder Aug 06 '19 at 08:57
  • 1
    wow, i see now why no one wants to use regex for this question. Thanks for your help! – raeign Aug 06 '19 at 09:08