Which Solution is Preferable? - Intermediate Algorithm Scripting - Pig Latin

Hi All,

I just completed the “Pig Latin” Intermediate Algorithm Scripting Challenge. I came up with two ways to write the solution.

Solution 1 is shorter but I think it’s less clear what the code is doing.

Solution 2 is longer and uses a switch, but I feel like it’s easier to understand what the code is doing.

Could you tell me which one you prefer (longer but easier to understand, or shorter but harder to understand) and why? Would also appreciate any suggestions on how I could complete this challenge with less code.

Thanks in advance!

Solution 1

function translatePigLatin(str) {
  let consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
  let vowels = ['a', 'e', 'i', 'o', 'u'];
  let charArray = str.split("");
  
if (charArray.every(letter => {return consonants.includes(letter)})) {
  charArray.push("a", "y")
}
else if (consonants.includes(charArray[0])) {
for (let i = 0; i < charArray.length; i++) {
if (consonants.includes(charArray[i])) {
  charArray.push(charArray[i]);
  delete charArray[i];
 }
 else {
   charArray.push("a", "y");
   break;
 }}}
else {
  charArray.push("w","a","y")
}
str = charArray.join(""); 
  return str;
}

translatePigLatin("rhythm");

Solution 2

function translatePigLatin(str) {
 let consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
 let vowels = ['a', 'e', 'i', 'o', 'u'];
 let charArray = str.split("");
 let whatAmI;

if (charArray.every(letter => {return consonants.includes(letter)})) {
whatAmI = "allConsonants";
}
else if (consonants.includes(charArray[0])) {
whatAmI = "startsWithConsonant";}
else {
whatAmI = "startsWithVowel";
}

 switch (whatAmI) {
   case "allConsonants":
     charArray.push("a", "y");
     break;
   case "startsWithConsonant":
     for (let i = 0; i < charArray.length; i++) {
     if (consonants.includes(charArray[i])) {
     charArray.push(charArray[i]);
     delete charArray[i];}
     else {
     charArray.push("a", "y");
       break;
       }};
     break;
   case "startsWithVowel": 
     charArray.push("w","a","y");
     break;
     }

str = charArray.join(""); 
 return str;
}

translatePigLatin("rhythm");
   **Your browser information:**

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

Challenge: Intermediate Algorithm Scripting - Pig Latin

Link to the challenge:

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