someuser2491
someuser2491

Reputation: 1968

How to refactor the ternary operator code using react and typescript?

i am getting the color based on the variable books and pens. if books or pens value is 0 apply red, value is 1 apply blue else green.

From code below the code is redunant meaning i am applying same colors based on value. how can i refactor it such that it can be be simplified further.

Below is the code,

const booksCountColor =
    books === 0
        ? red
        : books === 1
        ? blue
        : green;
const pensCountColor =
    pens === 0
        ? red
        : pens === 1
        ? blue
        : green;

Could someone help me with this. thanks.

Upvotes: 2

Views: 504

Answers (2)

wentjun
wentjun

Reputation: 42526

The problem with nested ternary statements/if else statements is that it can be rather messy. You can consider rewriting it by using the early return pattern to keep things clean.

const booksCountColor = () => {
  if (books === 0) {
    return red;
  }

  if (books === 1) {
    return blue;
  }

  return green;
};

const pensCountColor = () => {
  if (pens === 0) {
    return red;
  }

  if (pens === 1) {
    return blue;
  }

  return green;
};

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370699

Nested conditionals are awful for readability. I'd make an array instead, and alternate with green:

const colors = [red, blue];
const booksCountColor = colors[books] || green;
const pensCountColor = colors[pens] || green;

You could make it a bit DRY-er by putting it into a function

const colors = [red, blue];
const getColor = index => colors[index] || green;
const booksCountColor = getColor(books);
const pensCountColor = getColor(pens);

Upvotes: 1

Related Questions