Pig Latin, For loop Solutions

Pig Latin, For loop Solutions
0

#1

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


#2

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.


#3

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


#4

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.


#5

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.

In the future, please avoid posting a full working solution. If you have specific questions about a section of code, just post the section and ask your question.

Thank you.

Not sure why you think you must solve this challenge with a regular expression. Unless a challenge specifically tells you to solve a challenge in a particular way, you are free to solve using any code you want.