Algorithm Pig Latin - how bad is my solution?

function translatePigLatin(str) {
var arr = str.split(“”);
var vowels = [“a”, “e”, “i”, “o”,“u”];
var pigCons = “ay”;
var pigVow = “way”;
if (arr[0]===“a” || arr[0]===“e” || arr[0]===“i” || arr[0]===“o” || arr[0]===“u”){

arr.push(pigVow);
return arr.join("");

}

else {
for (i=0;i<arr.length;i++){
while (arr[i]!=“a” & arr[i]!= “e” & arr[i]!= “i” & arr[i]!= “o” & arr[i]!= “u”){
arr.push(arr[i]);
arr.shift();

}
var res = arr.join(“”);
return res.concat(pigCons);
}

  }

}
translatePigLatin(“california”);

So, I solved it, but, what do you experienced devs think about the code? Is this a bad solution, as I do have that feeling? Haven’t looked at other peoples solutions, yet.

Ohh, yes, I forgot about that - that is a leftover from another approach I have tried first…

I need to look at your solution (which looks really neat) and try to understand it - not so good with regexp yet…

Thank you very much for your insight.

Hi. I solved this with the array route (declared var vowels = ['a', 'e', 'i', 'o', 'u']; I didn’t know regex back then), and you can replace

if (arr[0]==="a" || arr[0]==="e" || arr[0]==="i" || arr[0]==="o" || arr[0]==="u")

with this:

if (vowels.includes(arr[0]))
1 Like

That is great - I didn’t know any method for simplifying my code,and that’s exactly what I wanted.

@P1xt, I understood your code, I like it very much. I have to dive into regexp - seems like many problems could be solved with few lines of code with the help of regexp.

A chapter in Eloquent JavaScript covers regex. :wink:

1 Like