Pig Latin using ternary operator

Tell us what’s happening:

I was able to solve the problem but when I try to use ternary operator for the if-else statement, it doesn’t seem to be working.
any ideas?

Your code so far


function translatePigLatin(str) {
  
  if(/^[aeiou]/.test(str)){
    return str.concat("way");
  } else {
    return str.replace(/^([^aeiou]+)/, '').concat(str.match(/^[^aeiou]+/), "ay"); 
  }
}

console.log(translatePigLatin("california"));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

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

  1. Why do you want to use a ternary?
  2. What does your ternary look like?

This worked for me:

function translatePigLatin(str) {
  return /^[aeiou]/.test(str) ? str.concat("way") : str.replace(/^([^aeiou]+)/, '').concat(str.match(/^[^aeiou]+/), "ay")
}

console.log(translatePigLatin("california"));

In the console:

aliforniacay
[Finished in 0.863s]

General pattern: return condition? returnValue1 : returnValue2;

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

Understood. Will do better.

You can do a FOREACH and use the ternary operator as follows.

test2 = FOREACH test GENERATE (b==‘1’ ? ‘abc’ : (b==‘2’ ? ‘xyz’ : a)) AS a, b;
Example using a ternary operator to check if a value is null and replace it with zero if it is.
ternary_null.pig
data = LOAD ‘input’ using PigStorage(’,’) AS (val:INT);

dump data;
– (1)
– ()

data2 = FOREACH data GENERATE (val IS NOT NULL ? val : 0) as result;

dump data2;
– (1)
– (0)
to join this conversation on GitHub. Already have an account? Sign in to

I don’t have to use it but I have to know how to use it… does that make sense ??
my ternary looked just like the one posted but without the return before it. I don’t know why I forgot to add it :slight_smile: thanks all