2

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.

2
  • Will the count be 2 in case of green? Commented May 5, 2020 at 8:37
  • anything above 1 Commented May 5, 2020 at 8:37

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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;
};

3 Comments

true this is easy to read...but we have a pattern to use only ternary when possible.
Questionable pattern imo, ternary is fine for short non nested conditions, but it gets messy quickly.
single-layered ternary and if else statements are fine. The only issue is when you start nesting them. nested ternary operators is actually one of the rules stated in eslint (eslint.org/docs/rules/no-nested-ternary)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.