Pig Latin It's good, but good enough?

Tell us what’s happening:

The code works, but I want to know if it’s good practice to define the variables inside a block like I did in one of the “ifs”. I also want to know if my code is understood. The answers given by the “hint” are shorter or cleaner, so I want an opinion about my code. Thank you and sorry for the inconvenience.

Your code so far


function translatePigLatin(str) {
let firstRule = /^([^aeiou])/;
let secondRule = /^([aeiou])/;
let thirdRule = /([aeiou])/g;

if (thirdRule.test(str) == false) {
  str += "ay";
  console.log("Third Rule");
}else if (secondRule.test(str)) {
  str += "way";
  console.log("Second Rule");
}else if (firstRule.test(str)) {
  let regex = /[aeiou]/g;
  let vowelIndex = str.search(regex);
  let consonants = str.substring(0,vowelIndex);
  let strCut = str.substring(vowelIndex);

  str = strCut + consonants + "ay";
  console.log("First Rule");
}
return str;
}
console.log(translatePigLatin("california"));

Your browser information:

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

Challenge: Pig Latin

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin

That is fine. I would however avoid using generic variables names like firstRule, secondRule, and thirdRule. Variable names should describe the values they represent.

I would change firstRule to something like notVowelRegex.

Couple of things to consider:

  1. You do not need the parentheses in any of these particular regular expression.

  2. There is no reason to declare the regex variable in the 2nd else if statement code block, because thirdRule is the same. You could just reference it to keep your code DRY (Do Not Repeat Yourself).

  3. if (thirdRule.test(str) == false) { can be simplified to the following:

    if (!thirdRule.test(str)) {
    
1 Like

One more thing I just noticed. You technically can get rid of either firstRule or secondRule and then modify your two else if statement conditions accordingly.

Bonus: You can get by with just an else statement instead of the last else if statement.

1 Like

I’ll try to do what you say, thank you for your help.