James Whiteley
James Whiteley

Reputation: 3474

How do I declare a variable in the output of a Javascript ternary operator?

I am trying to teach myself about Ternary Operators, and am stuck on a problem. To best explain what I am trying to do, below is pseudocode of what I want my code to look like:

const regex = /\d+k\d+/;
const input = "8k4";

const response = (!regex.test(input) ? "Regex does not match." : (
  const roll = input.substring(0);
  const keep = input.substring(2);
  (parseInt(roll) >= parseInt(keep) ? "Correct Format!" : "Keep is greater than Roll." )
);

console.log(response);

In essence, I am trying to replicate something like the following if/else code but using ternary operators (in order to condense my code), and I cannot seem to find the correct format for declaring the const bits in the second condition of the ternary operation:

const response = function() {
    if(!regex.test(input)) {
    return "Regex does not match.";
  } else {
    const roll = input.substring(0);
    const keep = input.substring(2);
    if(parseInt(roll) >= parseInt(keep)) {
      return "Correct Format!";
    } else {
      return "Keep is greater than Roll."
    }
  }
}();

For context, I am building a dice-rolling Discord Bot using discord.js so my friends and I don't need to be together to play tabletop games in the same place, hence the "roll" and "keep" variables.

Upvotes: 2

Views: 267

Answers (4)

rmn
rmn

Reputation: 1169

This answer develops on Luca's answer above. But further removes the non-required parentheses and makes use of unary plus operator to convert string to integer.

const response = regex.test(input)
? +input.substring(0) >= +input.substring(2) ? 'Correct Format!' : 'Keep is greater than Roll.'
: 'Regex does not match.'

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a helper function for comparing values and spread the splitted values to the function

const
    regex = /\d+k\d+/,
    input = "8k4",
    compare = (a, b) => +a >= +b,
    response = !regex.test(input)
        ? "Regex does not match."
        : compare(...input.split('k'))
            ? "Correct Format!"
            : "Keep is greater than Roll.";

console.log(response);

Upvotes: 3

Luca Kiebel
Luca Kiebel

Reputation: 10096

You can't have variable declarations inside of another variable declaration, other than that, your pseudocode works:

const regex = /\d+k\d+/;
const input = "8k4";

const response = (!regex.test(input) ? "Regex does not match." : (
  parseInt(input.substring(0)) >= parseInt(input.substring(2)) ?
  "Correct Format!" : "Keep is greater than Roll." )
)

console.log(response)

Upvotes: 2

johnheroy
johnheroy

Reputation: 416

I don't think you can have multiline expressions in the last part of your ternary statement (after :)--you could try putting that into a function and calling it from the outermost ternary.

Upvotes: 0

Related Questions