How to simplify multiple if statements javascript? - javascript

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?

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

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]

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 )

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

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
}

a?setIconA():b?setIconB:c?setIconC;d?setIconD
and
status == "active" ? setGreen() : status == "onhold": setYellow()
and so on.

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

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");

Related

React (Material UI) - MakeStyles with switch

So I have a button thats suppose to change the backgroundcolor depending on a variable (props.status), which is an int.
I can understand that its possible to swap between two values e.g. using something like backgroundColor: props.status ? 'red' : 'blue', but what if I have many colors?
Kinda assumed something like this would work, but it doesn't.
backgroundColor: (() =>
{
switch (props.status)
{
case 0:
return 'red'
case 1:
return 'red'
default:
break;
}
})
You need to execute the function that you just declared:
(() => {
//...
})() // note the last pair of parentheses
This pattern is called IIFE

Pattern matching in JavaScript?

I need to create a variable in JavaScript and assign it's value based on a condition. This works but feels a bit verbose:
const color = (() => {
switch (type) {
case "primary":
return CONSTANTS.colors.primary;
case "secondary":
return CONSTANTS.colors.secondary;
case "tertiary":
return CONSTANTS.colors.tertiary;
case "positive":
return CONSTANTS.colors.positive;
case "negative":
return CONSTANTS.colors.negative;
case "disabled":
return CONSTANTS.colors.disabled;
default:
throw new Error("A backgroundColor condition was missed");
}
})();
Is what I'm trying to do called "pattern matching"? Ive read that JavaScript doenst have this feature but Im not totally sure what it is.
Is there a more concise way of writing the code above? I could have lots of if statement but this feels messier and requires the variable to be let not const.
let color:
if (type === "primary") {
color = CONSTANTS.colors.primary;
} else if(type === "secondary") {
color = CONSTANTS.colors.secondary;
} else if(type === "tertiary") {
color = CONSTANTS.colors.tertiary;
} else if(type === "secondary") {
color = CONSTANTS.colors.secondary;
} else if(type === "positive") {
color = CONSTANTS.colors.positive;
} else if(type === "negative") {
color = CONSTANTS.colors.negative;
} else if(type === "disabled") {
color = CONSTANTS.colors.disabled;
}
The easiest solution for your problem is to check if the type is defined in the object CONSTANTS.colors. If you want to access a property by variable, you need to use the bracket annotation. Everything inside the brackets is evaluated as an expression (so type is a variable, 'type' the String value). Therefore, object.type returns the same value as object['type'].
let color = null;
if (typeof CONSTANTS.colors[type] !== 'undefined') {
color = CONSTANTS.colors[type];
} else {
throw new Error('A backgroundColor condition was missed');
}
console.log(color);
You can also first check if the key is defined in the object with Object.keys() and includes():
let color = null;
if (Object.keys(CONSTANTS.colors).includes(type)) {
color = CONSTANTS.colors[type];
} else {
throw new Error('A backgroundColor condition was missed');
}
console.log(color);
If you want to support IE11, you cannot use .includes(). Use .indexOf(type) !== -1 instead of .includes(type).
Pattern matching is generally referring to matching arguments passed to a function: testing to see if they match a specific "pattern". For example, a pattern match might allow you to write a function that takes an integer argument in "two different ways", one where the argument passed in is 0 and one when the argument passed is not 0 (the "otherwise" case). Switch statements are somewhat similar to this type of branching logic but aren't the same as a purely functional language like Haskell, and don't quite help with your goal here.
How about something like this instead?
const myColor = CONSTANTS["colors"][type];
if(typeof myColor !== 'undefined') {
color = myColor;
} else {
throw new Error("A backgroundColor condition was missed");
}
You are looking for property accessor:
color = CONSTANTS.colors[type];
An easy replacement for your code would be
const color = (() => {
const color = CONSTANTS.colors[type];
if (!color) {
throw new Error("A backgroundColor condition was missed");
}
return color;
}
})();
And no, that is not pattern matching.
I think it is wise to introduce an Enum that will hold the color values.
var ColorType = {
Primary: "primary",
Secondary: "secondary",
Tertiary: "tertiary,
...
};
Then you can use this enum in switch case and you will avoid the typos and referrence to string directly.
I think it will make the code less verbose and less prone to errors.
You can access a property of an object by using the property name as a string in square brackets.
(This example doesn't include the error catching you were using in your switch statement, but you can add that.)
const CONSTANTS = {
colors: {
primary: "blue",
secondary: "yellow"
}
}
function getColor(myPropName){
// Pass dynamic property names like this
return CONSTANTS.colors[myPropName];
}
console.log(getColor("secondary"));

Switch statement to match several cases

I want to write a switch statement that will go through first 2 cases if they are both true. If not, only match the one that is true.
var vehicle = {main: false, detail: false};
switch(true) {
case (states.data.currentState.indexOf('main.vehicle') !== -1):
vehicle.main = true;
break;
case (states.data.currentState === 'main.vehicle.detail):
vehicle.detail = true;
break;
}
My problem is that after first break the switch statement ends and doesn't go to case 2. However if I remove break from first case it will jump to case 2 and apply vm.vehicle.detail = true; even though the case condition isn't met.
So if I remove break in the first case, my object will look like this anyway
{ main: true, detail: true }
If I don't it will look like this
{ main: true, detail: false }
How do I meet both conditions on single run of the switch?
Why not just take the comparisons as values for the object?
var vehicle = {
main: states.data.currentState.indexOf('main.vehicle') !== -1,
detail: states.data.currentState === main.vehicle.detail
};
ES6
var vehicle = {
main: states.data.currentState.includes('main.vehicle'),
detail: states.data.currentState === main.vehicle.detail
};

how to bundle cases for "data-" attributes in a switch statement?

I'm running a switch statement with fairly many cases handling data-attributes.
Currently I'm stuck with this:
switch(attribute) {
case "value":
case "data-vv-validations":
case "data-relation":
case "data-tolerance":
case "data-theme":
case "type":
case "readonly":
case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
I'm wondering if it's possible to combine all data- attributes into a single case, because listing all possible options I'm running into is kind of "not generic"...
Question:
In CSS selectors I can do somethink like [class*=" ui-icon-"]. Can I also make the case value more generic?
Thanks!
Sort of. You can see if the first characters are "data-, and if so, just use those chars for the switch.
var a = attribute.slice(0, 5) === "data-" ? "data-" : attribute;
switch(a) {
case "value": case "data-": case "type": case "readonly": case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
This reduces all data- attributes to a single testable value. Note that you still use the full attribute with the setters[].
Or since you already seem to have the attribute names in a setters map, you could just do this:
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
Your switch seemed to be redundant since you were almost performing the same test when you do this:
if (setters[attribute]) {
Or if you need to test specifically the name, then...
if (setters.hasOwnProperty(attribute) && setters[attribute]) {
Simply solved with something like this:
var attributeSwitch = attribute.indexOf("data-") == 0 ? "data-*" : attribute;
case(attributeSwitch){
case "value":
case "data-*":
case "type":
case "readonly":
case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
No, you can't make "generic case statements".
But you can use an array of possible values and then check if the value is one of those.
function inArray(array, value) {
for(var i=0, len=array.length; i<len; i++) {
if(array[i] == value) {
return true;
}
}
return false;
}
var possibleValues = ["value",
"data-vv-validations",
"data-relation",
"data-tolerance",
"data-theme",
"type",
"readonly",
"size"];
if (setters[attribute] && inArray(possibleValues, attribute)) {
element.setAttribute(attribute, setters[attribute]);
}

Why isn't my switch block (switching on $(e.target) .attr("class")) working?

I am trying to figure out why this code doesn't work..
All i want is to have simple event delegation to assign one event listener.
it only alerts, it doesn't animate.
Please let me know whats wrong here:
$(document).ready(function() {
var img = $("img");
$("span").click(function(e){
var targetClicked = $(e.target).attr('class');
//the alert works fine
alert(targetClicked)
switch(targetClicked){
// i deleted the rest of the cases
case d:img.stop(false,true);
break;
case e:img.slideDown().animate({"width":200, height:200, opacity:0.4,});
break;
//nothings works here as well
case f:alert("hi");
break;
}
});
});
What are d and e in your switch statement case conditions? The way you're code is written right now, they're being treated as variables and your code is probably blowing up with a "'d' is undefined" error.
If you want to switch on the class names "d" and "e", then you need to use the class names as strings:
switch (targetClicked) {
case "d":
//...
break;
case "e":
// ...
break;
}

Categories

Resources