Pig Latin, For loop Solutions

This works for me but I noticed the task was meant to be solved with regular expression, is there a performance issue between using regular expressions and loops?

Your code so far


 function translatePigLatin(str) {
   for (let i = 0; i < str.length; i++)
   {
    if (str.charAt(i) === 'a'|| str.charAt(i) === 'e'|| str.charAt(i) === 'i'||
      str.charAt(i) === 'o'|| str.charAt(i) === 'u')
      {

        if (i === 0)
        {
          return str+"way";
        }
        return str.slice(i,str.length)+str.slice(0,i)+"ay";

      }
   }
  return str+"ay";
}

translatePigLatin("consonant");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin

There’s likely to be little difference in performance; there will be some overhead with regex, but it’ll make little practical difference in this case. Code using regex will be easier for someone reading it to understand, but you can solve it any way you want.

1 Like

Thank you. I just have a hard time with regexp, I’ll pay more attention to it now

The only reason it’s easier to understand is because a regex solution will read:

if the string matches this pattern:
  do this
else if it matches this pattern:
  do this
else:
  do this
etc

Whereas with a loop, it isn’t clear immediately what you’re trying to do you have to carefully read the code to figure out how the logic works.

1 Like