Pig Latin [Algorithm Scripting] *SOLVED*

Pig Latin [Algorithm Scripting] *SOLVED*
0.0 0

#1

So i’m trying to do what the challenge says, moving the first consonants to the end of the string with an "ay" and it works but but i can’t find a way to apply this algorithm when it needs to move more than one consonant from the first.
ex :

translatePigLatin("glove") should return "oveglay".

this algo is only working for one letter to move to the end.
Can someone point out where i’m making any mistake.
Here is the code :


function translatePigLatin(str) {
  var arr = str.split("");
  var newStr="";
  for(let i=0;i<arr.length;i++){
    if(arr[i]==='a'||arr[i] === 'e'||arr[i] === 'i'||arr[i] === 'o'||arr[i] === 'u'){
    return str+"way";
  }else{
    newStr=str.substr(a[i]);
    return newStr+arr[i]+"ay";
  }
}
}
translatePigLatin("consonant");

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin
[@randelldawson little help plz]


#2

First of all you have an error message showing up when running the tests. The error is:
a is not defined

You are getting the above message, because in the following line of code, you reference a variable named a, but you have not defined this variable before using it.

newStr=str.substr(a[i]);

My guess is you meant to type another existing variable, but I will let you sort that out.

Once you resolve the issue above, you will find another issue in your logic. As soon as your code encounters a return statement, the function returns the specified value but also immediately exits the function. Even if a for loop has not completed, the function is exited. In the test case translatePigLatin(“glove”); this means the first letter is not a vowel, so your else block of code executes and newStr gets assigned “glove” and then you return newStr concatenated with “g” + “ay” to result in “glovegay”.

If you have not already done so, you need to write out the steps of how you would convert “glove” into “oveglay” by hand without a computer. Think about how you would iterate through the given string and then which parts of the string you would really need to concatenate together.


#3

Now it says to handle words without vowels , But i guess i handled it at first test . right ?? then where is the problem now ?

My code : -------

function translatePigLatin(str) {
  var firstWord=str[0];
  var vowels=/[aeiou]/gi;
  var newStr="";
  if(!str.match(vowels)){
    return str;
  }
  if(firstWord.match(vowels)){
    newStr= str+'way';
  }else{
    var indexOfVowel=str.indexOf(str.match(vowels)[0]);
    newStr=str.substr(indexOfVowel)+str.substr(0,indexOfVowel)+'ay';
  }
  return newStr;
}

#4

Oh damn it. im so stupid . i just have to add 'ay' to the end of str at :

if(!str.match(vowels)){
    return str+'ay';
  }

Now its done. pheewwww. thanks again :slight_smile: