E
E
EvgenyJozef30002019-05-31 19:16:37
JavaScript
EvgenyJozef3000, 2019-05-31 19:16:37

What is the best way to optimize and make my JavaScript code shorter?

I have the following JS code:

if (floors.value == 1) {
  if (area.value <= 120) {
    a1 = 1.26;
  } else {
    a1 = 1; 
  }
  
  if (area.value >= 120.001 && area.value <= 140) {
    a2 = 1.24;
  } else {
    a2 = 1;
  }
  
  if (area.value >= 140.001 && area.value <= 160) {
    a3 = 1.23;
  } else {
    a3 = 1;
  }
  
  if (area.value >= 160.001 && area.value <= 200) {
    a4 = 1.22;
  } else {
    a4 = 1;
  }

  if (area.value >= 200.001 && area.value <= 260) {
    a5 = 1.2;
  } else {
    a5 = 1;
  }
  
  if (area.value >= 260.001 && area.value <= 300) {
    a6 = 1.19;
  } else {
    a6 = 1;
  }
  
  aF = a1*a2*a3*a4*a5*a6;
  console.log(aF);
} else if (floors.value == 2 || floors.value == 3) {
  if (area.value >= 100 && area.value <= 130) {
    b1 = 1.3;
  } else {
    b1 = 1;
  }
  
  if (area.value >= 130.001 && area.value <= 160) {
    b2 = 1.27;
  } else {
    b2 = 1;
  }
  
  if (area.value >= 160.001 && area.value <= 200) {
    b3 = 1.24;
  } else {
    b3 = 1;
  }
  
  if (area.value >= 200.001 && area.value <= 300) {
    b4 = 1.22;
  } else {
    b4 = 1;
  }
  
  bF = b1*b2*b3*b4;
  console.log(bF);
}

What is the best way to optimize and make my JS code shorter (not pretty)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2019-05-31
@EvgenyJozef3000

Sequential segments of a supposedly continuous range are described. The jamb is that for values ​​between, say, 120and 120.001, the conditions are not defined and the code will give an error, because one of the variables is not defined.
So chain is better else if. Since they are multiplied and default to units, you can immediately determine the final value:

if (floors.value == 1) {

  aF = 1; // по умолчанию, для больше 300
  
  if (area.value <= 120) aF = 1.26;
  else if (area.value <= 140) aF = 1.24;
  else if (area.value <= 160) aF = 1.23;
  else if (area.value <= 200) aF = 1.22;
  else if (area.value <= 260) aF = 1.2;
  else if (area.value <= 300) aF = 1.19;

  console.log(aF);
  
} else if (floors.value == 2 || floors.value == 3) {
  
  bF = 1; // ? для меньше 100 .. и больше 300
  
  if (area.value >= 100 && area.value <= 130) bF = 1.3;
  else if (area.value <= 160) bF = 1.27;
  else if (area.value <= 200) bF = 1.24;
  else if (area.value <= 300) bF = 1.22;

  console.log(bF);

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question