My solution to Pig Latin

My solution to Pig Latin
0

#1
function translatePigLatin(str) {
  str=str.split('');
 var newStr="";
     if (str.indexOf('a')===0) {
       str.push('w','a','y');
       return str.join('');
     }
     else if (str.indexOf('e')===0) {
       str.push('w','a','y');
       return str.join('');
     }
     else if (str.indexOf('i')===0) {
       str.push('w','a','y');
       return str.join('');
     }
     else if (str.indexOf('o')===0) {
       str.push('w','a','y');
       return str.join('');
     }
     else if (str.indexOf('u')===0) {
       str.push('w','a','y');
       return str.join('');
     }
     else {
       newStr=str.shift();
     }
        if (str.indexOf('a')===0) {
          str.push(newStr,'a', 'y');
        }
        else if (str.indexOf('e')===0) {
       str.push(newStr,'a', 'y');
     }
     else if (str.indexOf('i')===0) {
       str.push(newStr,'a', 'y');
     }
     else if (str.indexOf('o')===0) {
       str.push(newStr,'a', 'y');
     }
     else if (str.indexOf('u')===0) {
       str.push(newStr,'a', 'y');
     }
     else {
       newStr+=str.shift();
       if (str.indexOf('a')===0) {
          str.push(newStr,'a', 'y');
        }
        else if (str.indexOf('e')===0) {
       str.push(newStr,'a', 'y');
     }
     else if (str.indexOf('i')===0) {
       str.push(newStr,'a', 'y');
     }
     else if (str.indexOf('o')===0) {
       str.push(newStr,'a', 'y');
     }
     else if (str.indexOf('u')===0) {
       str.push(newStr,'a', 'y');
     }
     
  
   
 
}
return str.join('');
}

This was embarassingly bad . . .


#2

I’ve edited your post to make it readable. When putting a code block, please put three backticks (key below the ESC) on the line before, and another on the line after so it formats nicely.


#3

Now that that’s done, let’s look at your code.

Yes, that is ugly.

Why check if all those things are str.indexOf('u')===0? Why not just str[0]==='u'. And instead of those long chains of if/else if, you can use a logical or, ||. What about something like:

if (str[0]==='a' || str[0]==='e' || str[0]==='i' || str[0]==='o' || str[0]==='u') {
  // do what you want

That would clean things up a bit.

There are other ways to do it more simply, but I don’t want to pull you too far away from your solution.


#4

Lol Thanks. I looked up the solution after and I learned a lot from it. I knew that the trajectory i was going on with my solution was going to work out in the end and had tunnel vision and wanted to just solve it as quick as possible. I just thought it was hilarious how bad it was yet it passed. Turns out I needed regular expressions to do it the way I originally wanted to and learning it now.