JoshG
JoshG

Reputation: 6735

Cleaning up complicated/unreadable if statements with multiple uses of typeof operator

I have a JavaScript object containing which axes data are plotted on. I need to use this to determine if it is a 2D plot (with data on X/Y, Y/Z, or X/Z) or a 3D plot (with data on X/Y/Z).

The below code works and I believe covers all of these cases. But it's pretty unreadable and complex. Is there any way to improve on this to make it more readable and/or simple?

Thanks in advance for any and all assistance.

var axes = {
    "X": "Column 1",
    "Y": "Column 2",
    "Z": "Column 3"
}

if (typeof axes.X == 'undefined' && typeof axes.Y !== 'undefined' && typeof axes.Z !== 'undefined') {
    alert("2D plot on Y and Z");
} else if (typeof axes.X !== 'undefined' && typeof axes.Y !== 'undefined' && typeof axes.Z == 'undefined') {
    alert("2D plot on X and Y");
} else if (typeof axes.X !== 'undefined' && typeof axes.Y == 'undefined' && typeof axes.Z !== 'undefined') {
    alert("2D plot on X and Z");
} else if (typeof axes.X !== 'undefined' && typeof axes.Y !== 'undefined' && typeof axes.Z !== 'undefined') {
    alert("3D plot");
}

Upvotes: 0

Views: 49

Answers (2)

David
David

Reputation: 7105

Looking at your code, it looks like just using truthy/falsey values could be used to simplify the statements and keep them clear.

var axes = {
    "X": "Column 1",
    "Y": "Column 2",
    "Z": "Column 3"
};

if (!axes.X && axes.Y && axes.Z) {
    alert("2D plot on Y and Z");
} else if (axes.X && axes.Y && !axes.Z) {
    alert("2D plot on X and Y");
} else if (axes.X && !axes.Y && axes.Z) {
    alert("2D plot on X and Z");
} else if (axes.X && axes.Y && axes.Z ) {
    alert("3D plot");
}

Upvotes: 2

rkmax
rkmax

Reputation: 18135

you can use a loop

var axes = {
    "X": "Column 1",
    "Y": "Column 2",
    "Z": "Column 3"
}

var axesChecked = [];

for (var prop in axes) {
  if(axes.hasOwnProperty(prop) && typeof axes[prop] !== 'undefined'){
    axesChecked.push(prop);
  }
}

switch(axesChecked.length) {
  case 3:
    alert("3D plot");
    break;
  case 2:
    alert("2D plot " + axesChecked.join(' and '));
    break;
  default:
    throw "Need more axes";
    break;
}

Upvotes: 3

Related Questions