Please help me understand this Pig Latin solution

I’ve solved the Pig Latin scripting challenge and reviewed all of the given solutions but the final one confuses me. Could anyone explain to me exactly what this code does please?

function translatePigLatin(str, charPos = 0) {
  return ['a', 'e', 'i', 'o', 'u'].includes(str[0])
 	   ? str + (charPos === 0 ? 'way' : 'ay')
    : charPos === str.length
      ? str + 'ay'
  	    : translatePigLatin(str.slice(1) + str[0], charPos + 1);
}

What this code primarily does is annoy anyone who has to read and make sense of it :smiling_imp:

It uses nested ternaries as a replacement for if/else statements. Ternaries are great when you have a simple condition like

function isFirstLetterAVowel(str) {

  return ['a', 'e', 'i', 'o', 'u'].includes(str[0]) 
      ? 'first letter is a vowel' 
      : 'first letter is no vowel';
}

This is the same as:

function isFirstLetterAVowel(str) {

  if (['a', 'e', 'i', 'o', 'u'].includes(str[0]) {
    return 'first letter is a vowel'
  } else {
    return 'first letter is no vowel'
  }
}

Has that already answered the question?

2 Likes

It’s also a recursive function. Without the ternaries (I think I got it) if that helps.

function translatePigLatin(str, charPos = 0) {
  if (['a', 'e', 'i', 'o', 'u'].includes(str[0])) {
    if (charPos === 0) {
      return str + 'way';
    } else {
      return str + 'ay';
    }
  } else if (charPos === str.length) {
    return str + 'ay';
  } else {
    return translatePigLatin(str.slice(1) + str[0], charPos + 1);
  }
}
1 Like

Thanks for the replies. Yes, I understand that the ternary operator is a shorthand for if/else and I guess I would have found the code easier to understand presented the way you have, but it still takes a bit to wrap my head around so many nested conditional statements with recursion thrown in to boot!

My solution for this challenge was much more predictable and straightforward:

function translatePigLatin(str) {
if (str.match(/^[aeiou]/)) {
return str+“way”;
}
let consonants = /^[^aeiou]+/
return str.replace(consonants, “”)+str.match(consonants)+“ay”;
}

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