Gurkiran Singh
Gurkiran Singh

Reputation: 117

Writing nested if else into ternary operator

I have nested if else statement, is there any solution for turning this into ternary operator ?

let widthStyledMeter;
if (direction === 'horizontal') {
    if(size === "full"){
      widthStyledMeter = '100%';
    }else{
      widthStyledMeter = length;
    }
  } else {
    if(size === "full"){
      widthStyledMeter = '100%';
    }else{
      widthStyledMeter = thickness;
    }
  }

Upvotes: 0

Views: 366

Answers (2)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8188

This is how you can use a ternary operator:

let 
  widthStyledMeter,
  direction = "vertical",
  size = "100%",
  length = 100,
  thickness = 20;

direction === "horizontal"
  ? (widthStyledMeter = size === "full" ? "100%" : length)
  : (widthStyledMeter = size === "full" ? "100%" : thickness);

console.log(widthStyledMeter);

Also, since you're sure when size is "full" then widthStyledMeter will always be "100%", so its better to check size first and then direction.

let 
  direction = "vertical",
  size = "100%",
  length = 100,
  thickness = 20,
  widthStyledMeter =
    size === "full" ? "100%" : direction === "horizontal" ? length : thickness;

console.log(widthStyledMeter);

Upvotes: 1

savageGoat
savageGoat

Reputation: 1546

Even though this is way less readable, it would look like this:

const widthStyledMeter = size === "full" ? "100%" : (direction === 'horizontal' ? length : thickness);

You have a common value set here, wich is size == "full" = "100%", since it's there's no condition on the else statement you can reduce it to avoid a size = "full" double check

[Edit] A more readable way would be:

let widthStyledMeter;
if (size === "full") {
    widthStyledMeter = "100%";
} else {
    widthStyledMeter = direction === "horizontal" ? length : thickness ;
}

Upvotes: 1

Related Questions