Beginner applying ternary operator in Javascript for Pig Latin, but can't figure why it doesn't work

65 Views Asked by At

I'm stuck figuring out why the ternary operator won't return the negative output, and can't really figure out why. Here's the code:

function translatePigLatin(str) {
  let reg=/[aeiou]/gi;
  let firstVowel = str.indexOf(str.match(reg)[0]);
  //console.log(firstVowel);

  return str.match(reg) == 1 ? play(str) : str + "ay";
  
  function play(str) {
    if(str[0].match(reg)){
      return str+"way";
    }else if(str[1].match(reg)){
      return str.slice(1) + str[0]+ "ay"
    } else if(str.match(reg)!==null){
      return str.slice(firstVowel) +str.slice(0,firstVowel)+"ay";
    } else {
      return str+"ay";
    }
}
}
console.log(translatePigLatin("consonant"));
console.log(translatePigLatin("eight"));
console.log(translatePigLatin("glove"));
console.log(translatePigLatin("hmm"));

The last test with "hmm" results in error : "TypeError: str.match(...) is null".

I feel better understanding of what null means here could help, but unsure if it makes sense, and how to do so.

How might I better understand this, and make it work? Thanks!

1

There are 1 best solutions below

1
Ross Sheppard On

There is no match for the word "hmm", since there is no vowel with that string. You'll have to conditionalize your function to return a proper result. I updated the code below.

  • I took out your else if since you're returning a value in each condition anyway, so it wouldn't read any of the code after returning.
  • I didn't see a reason for two encapsulated functions.
  • I used template literals as well.
function translatePigLatin(str) {
   const reg = /[aeiou]/gi;
   const match = str.match(reg);
   const firstVowel = match ? str.indexOf(match[0]) : null;

   if (!firstVowel) {
     return `${str}ay`;
   }

   if (str[0].match(reg)) {
     return `${str}way`;
   }

   if (str[1].match(reg)) {
     return `${str.slice(1)}${str[0]}ay`;
   }

   if (str.match(reg)!== null) {
     return `${str.slice(firstVowel)}${str.slice(0,firstVowel)}ay`;
   }
 };

 console.log(translatePigLatin("consonant"));
 console.log(translatePigLatin("eight"));
 console.log(translatePigLatin("glove"));
 console.log(translatePigLatin("hmm"));