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?
What this code primarily does is annoy anyone who has to read and make sense of it
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'
}
}
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”;
}