8

I have multiple conditions to check. I have to add icons based on the conditions, Then I need to change the background color based on some other set of conditions. I am using if statement. This is my code.

JSON:

{
  "date": "2017-05-12",  
  "a": false,
  "b": true,
  "c": true,  
  "d": false,
  "status": "active"
}

Javascript:

 if (date != -1) {
  //do something
  if (a) {
    //Add icon a
  }
  if (b) {
    //Add icon b
  }
  if (c) {
    //Add icon c
  }
  if (d) {
    //Add icon d
  }
}

if(status == "active"){
  //Background Green
}
else if (status == "onhold"){
  //Background Yellow
}
else if (status == "inactive"){
  //Background Red
}
else{
  //Backgeound Grey
}

How do I simplify it?

4
  • You can use a Switch statement instead of if - else. Commented May 12, 2017 at 10:36
  • also see AND OR and other logical operators. They are also also helpful in combining different if-else conditions into a single condition. Commented May 12, 2017 at 10:39
  • 1
    Conditions such as if (a == true) can be simplified as if (a) Commented May 12, 2017 at 10:40
  • And if (a) someExpression can be simplified as a && someExpression. Commented May 12, 2017 at 10:46

8 Answers 8

9

The first half of you code looks fine. For the second half of your code you should make use of a switch statement. These replace the if-else statements you are using and decide what to do when certain "cases" occur. For example:

switch(status) {
    case 'active':
        //background green
        break;
    case 'onhold':
        //background yellow
        break;
    case 'inactive':
        //background red
        break;
    default:
        //background grey
        break;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Reduced my if-else code by 2/3. Very nice approach.
7

My idea is:

var icons = {
    a: 'a.png',
    b: 'b.png',
    c: 'c.png',
    d: 'd.png',
}

if (date != -1) {
    Object.keys(icons).forEach(function(key) {
        if (data[key]) {
            //Add icon icons[key]
        }
    });
}

var statusColors = {
    active: 'Green',
    onhold: 'Yellow',
    inactive: 'Grey',
}

//Background statusColors[status]

1 Comment

Faster than a switch?
1

I think it is pretty good as it is. Is is better to have understandable code than complex code that does exactly the same thing.

You don't have to do

if (a === true)

as it's equivalent to

if ( a )

Comments

0

There is no way to "simplify" it, but you can try to use switch statement instead:

switch (status) {
  case 'active':
    // active
    break;
  case 'onhold':
    // onhold
    break;
  case 'inactive':
    // inactive
    break;
  default:
    console.log('default');
}

You can even "group" some conditions:

switch (status) {
  case 'active':
  case 'onhold':
    // active AND onhold case
    break;
  case 'inactive':
    // inactive
    break;
  default:
    console.log('default');
}

More about switch statement -> https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch

Comments

0

For Status variable you can use switch but for the first condition you have to use if-else statements I think.

switch (status) {
        case "active":
            //Background Green
            break;
        case "onhold":
            //Background Yellow
            break;
        case "inactive":
            //Background Red
            break;
        default:
            //Backgeound Grey
    }

Comments

0

Your question doesn't quite give the details of the actions in each case, but if they're very similar, and there's a match between the property name and whatever action you need to take, you can use loops.

['a','b','c','d'].forEach(function (k)
{
    if (objectFromJSON[k])
    {
       addIcon(k);
    }
});

For the second part, it's slightly more complex as you have status names that don't match the color. You can either:

  • define CSS classes with those status names, and use the status name to set the class:

    CSS:

    .status-active
    {
        background: green;
    }
    .status-onhold
    {
        background: yellow;
    }
    .status-inactive
    {
        background: red;
    }
    

    JS:

    theHTMLobject.classList.addClass('status-'+objectFromJSON.status);
    
  • use an object's properties (or a Map) to convert the status into a color

Comments

0

Do you mean "simplify" or do you mean "shorten" - because the two are almost mutually exclusive (shorter code is often not simpler!)

Your code is clear, and understandable. But it is a bit verbose, and can get much more complex as things grow. Sometimes it is better to shorten and the risk of making it a bit harder to understand.

You could consider things like a map between the status and the appropriate color

var backgroundStatusMap = {
    "active":"green",
    "onhold": "yellow",
    "inactive": "red"
};

var backgroundColor = backgroundStatusMap[json.status];

Things like this can be added to easier if you as add new statuses - without having to trawl for the right place to put a new if.. condition.

Similarly, you could create a map for the booleans-to-icons

var iconMap = {
    "a":"icon_a.png",
    "b": "icon_b.png"
};

function getIcon(json, prop){
    if(json[prop])
      return iconMap[prop];
    return null;
}

var iconA = getIcon(json,"a");
var iconB = getIcon(json,"b");

Comments

-1

a?setIconA():b?setIconB:c?setIconC;d?setIconD

and

status == "active" ? setGreen() : status == "onhold": setYellow()

and so on.

Comments

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.