Pig latin - why do some words pass the test and others don't?

Pig latin - why do some words pass the test and others don't?
0.0 0

#1

Hi everyone,
Why is my Pig latin function not translating every word?
I have tried words with two consonants, two vowels, one consonant, one vowel, etc and most of them pass the tests but then some don’t, like “glove” and “eight”? Why?
Please don’t give me the code! Just point me in the right direction :slight_smile:
thanks!!

function translatePigLatin(str) {

  var vowels = ["a","e", "i", "o", "u", "A", "E", "I", "O", "U"];
  var word = str.split("");
  for (var i=0; i<vowels.length; i++) {
    if (str.charAt(0) != vowels[i]){
      if (str.indexOf(vowels[i]) == -1){
        break;
      }
        var chunk = str.substring(0, str.indexOf(vowels[i]));
        word.push(chunk, "ay");
        word.splice(0, str.indexOf(vowels[i]));
        str = word.join("");


    } else {

      word.push("way");
      str = word.join("");

    }
 }


 console.log(str);
 return str;
}

translatePigLatin("crack");

#2

If you look at the word “glove”, the following if statement evaluates to true in the first iteration where i = 0, str.charAt(0) = ‘g’, and vowels[0] = ‘a’

if (str.charAt(0) != vowels[i]){

Then the next if statement (seen below), you check if ‘a’ is not in str. Since ‘a’ is not in str which is ‘glove’, your code executes the break statment and the current value of str which is still ‘glove’ gets returned by your function.

if (str.indexOf(vowels[i]) == -1){

#3

Fixed it :slight_smile: used a regular expression instead of an array of vowels (I don’t now why I was trying to avoid the regular expression!). Much easier and shorter.

THANK YOU!