Home > OS >  How to make this multiple conditional if else block into shorter syntax - javascript?
How to make this multiple conditional if else block into shorter syntax - javascript?

Time:08-22

I have written a conditional block by using multiple if else-if statements. I have checked in various articles to avoid of using multiple if else. So, how to use enums for this multiple if-else conditions?

Here is the code:

if (!props.focusable) {
    svg = svg.replace("<svg ", '<svg focusable="false" ');
  }
  options.domProps = { innerHTML: svg };
} else {
  options.class.push("fa-"   iconName);
  if (props.brand) {
    options.class.push("fab");
  } else if (props.fab) {
    options.class.push("fab");
  } else if (props.regular) {
    options.class.push("far");
  } else if (props.far) {
    options.class.push("far");
  } else if (props.light) {
    options.class.push("fal");
  }  else if (props.fal) {
    options.class.push("fal");
  } else if (props.old) {
    options.class.push("fa");
  }  else if (props.fa) {
    options.class.push("fa");
  }  else {
    options.class.push("fas");
  }
}

How to make it shorter and better in performance wise?

CodePudding user response:

You can combine certain else-if's using OR operator:

if (!props.focusable) {
    svg = svg.replace("<svg ", '<svg focusable="false" ');
  }
  options.domProps = { innerHTML: svg };
} else {
  options.class.push("fa-"   iconName);
  if (props.brand || props.fab) {
    options.class.push("fab");
  } else if (props.regular || props.far) {
    options.class.push("far");
  } else if (props.light || props.fal) {
    options.class.push("fal");
  } else if (props.old || props.fa) {
    options.class.push("fa");
  } else {
    options.class.push("fas");
  }
}

CodePudding user response:

if (!props.focusable) {
    svg = svg.replace("<svg ", '<svg focusable="false" ');
  }
  options.domProps = { innerHTML: svg };
} else {
  options.class.push("fa-"   iconName);

  let cls = "fas";
  if (props.brand || props.fab) cls = "fab";
  if (props.regular || props.far) cls  = "far"; 
  if (props.light || props.fal) cls  = "fal"; 
  if (props.old || props.fa) cls  = "fa";

  options.class.push(cls);
}

Hope this help. Thanks!

CodePudding user response:

options.class.push("fa-"   iconName)
props.brands || props.fab ? options.class.push("fab") :
props.regular || props.far ? options.class.push("far") :
props.light || props.fal ? options.class.push("fal") :
props.old || props.fa ? options.class.push("fa") :
options.class.push("fas")

CodePudding user response:

yo can use switch statement .switch case use for multiple statement. read this for your referrence https://www.w3schools.com/js/js_switch.asp

  • Related