skip to Main Content

I am creating a calculator. Inside it, it is necessary to calculate the average of three variables, and now I am declaring an if else statement for when one of the three is equal to 0, it is to divide by 2. When two values ​​are equal to 0, it is to divide by 1. And case no value equals 0 divide normally. I’m programming in Wix using Velo. The message that appears is the following:

"This branch can never execute. Its condition is a duplicate or covered by previous conditions in the if-else-if chain. eslint(no-dupe-else-if)",

and if there are two numbers equal to zero, it continues dividing by 2, it is ignoring the second statement. Can someone help me? Here is my code:

I hope to be able to calculate the average with even if any value is 0.

if (preço1 === 0 || preço2 === 0 || preço3 === 0) {
  médiaPreços = (preço1 + preço2 + preço3) / 2;
} else if (preço1 && preço2 || preço1 && preço2 || preço2 && preço3 === 0) {
  médiaPreços = preço1 + preço2 + preço3;
} else médiaPreços = (preço1 + preço2 + preço3) / 3;

2

Answers


  1. You don’t need to test all the combinations of conditions. Just count the number of non-zero values to find out what to divide the total by.

    let countPreços = 0;
    if (preço1 != 0) {
        countPreços++;
    }
    if (preço2 != 0) {
        countPreços++;
    }
    if (preço3 != 0) {
        countPreços++;
    }
    
    if (countPreços > 0) {
        médiaPreços = (preço1 + preço2 + preço3) / countPreços;
    } else {
        médiaPreços = 0;
    }
    
    Login or Signup to reply.
  2. media = (preco1 + preco2 + preco3) / Math.max((preco1 > 0) + (preco2 > 0) + (preco3 > 0), 1)
    
    • As @barmar said, this thing that you are asking is not an average count
    • As @mplungjan said, it is not good practice to use diacritics in identifiers
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search