Intermediate Algorithm Scripting - Pig Latin

Tell us what’s happening:

Hey,

so I’m trying to not over complicate this, and I’m sure there are javascript function to make this much neater.

I think the problem is with my if inside the for loop, most likely .match. I also have way too many console.log but I am trying to find why it is not looping properly and not stopping when the first element of the array is the first vowel.

output

^^^^^^^^^^^^^^^^^^^^

start paragraphs
cons [ ‘p’, ‘a’, ‘r’, ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ] str.length 10
s loop 0 [ ‘p’, ‘a’, ‘r’, ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ]
loop 0 p [ ‘a’, ‘r’, ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ] a
s loop 1 p [ ‘a’, ‘r’, ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ]
loop 1 pa [ ‘r’, ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ] a
s loop 2 pa [ ‘r’, ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ]
loop 2 par [ ‘a’, ‘g’, ‘r’, ‘a’, ‘p’, ‘h’, ‘s’ ] r
break 3
join par agraphs
concat agraphspar
end agraphsparay

^^^^^^^^^^^^^^^^^^^^^^^

Your code so far

function translatePigLatin(str) {
  
  console.log("start", str);
  let con = /^[^aeiou]/;
  let vow = /^[aeiou]/;
 
  
  if (str.match(con)) {
    str = str.split("");
    let cons = [];
    console.log("cons", str, "str.length", str.length);
    
    for (let i = 0; i < str.length; i++) {
      if (str[i].match(con)) {
        console.log("s loop", i, cons, str);
        cons = cons + str.shift();
        console.log("loop",i ,cons, str, str[i]);
      } 
    
      else {
        console.log("break", i); 
        break;}
      
    }

    str = str.join("");
    toString(str);
    console.log("join", cons, str)
    str += cons;
    console.log("concat", str);
    str += "ay";
    console.log("end", str);
  return str;
  }

  
  else if (str.match(vow)) {
    str += "way";
    console.log(str);
    return str;
  }

  console.log("end", str)
}

translatePigLatin("paragraphs");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Pig Latin

Link to the challenge:

I’ve separated into two if

  • one if the first letter is not a vowel, made str into an array so I could use shift to remove consonants from the start of the str and put them into a new array which I want to add at the back before adding “ay”.

Outside of the for loop is working, but I don’t know if “if (str[i].match(con))” is the only issue or the else after is as well.

Worked it out thanks, was taking an element away and increasing i meaning it wasn’t checking the first character anymore

Thanks a lot!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.