DEV Community

Discussion on: Issue with Else If Statement

Collapse
 
nparekh1979 profile image
nparekh1979

I still am confused and my specific query is:

The condition that if the sum is greater than 10 and less than equal to 20 should have a surcharge to be added of 2 is also confusing. For this condition the surcharge to be added according to me can even be 3

I am a bit confused with the statement: else if (sum > 40) { return sum += 5}. I understand that if the sum is above 40 then there is a good chance that both the digits are above 20 and hence the surcharge should be 6 instead of 5. I cannot understand this at all and am surprised as to how the code has passed the test.

I am also confused as to why is there no else statement in the end, and why do I need to assume that the else statement will automatically identify the numbers above 20 and add 6 as a surcharge.

Can you simplify this for me.

Collapse
 
moopet profile image
Ben Sinclair

Let's cut it down a bit. This bit here is redundant:

  if ( sum < 10) {
    return sum += 2
  }
  else if (sum > 10 && sum <= 20) {
    return sum += 2
  }
Enter fullscreen mode Exit fullscreen mode

Because the first condition is always going to match if the second does, and they return the same thing.

If I cut out the stuff that's unnecessary but keep the same general structure, we can get to this:

function addWithSurcharge (a, b) {
  let sum = a + b;

  if (sum <= 20) {
    return sum += 2
  }

  if (sum <= 30) {
    return sum += 3
  }

  if (sum <= 40) {
    return sum += 4
  }

  return sum += 5
}
Enter fullscreen mode Exit fullscreen mode

I've taken out the redundant first condition and removed the last elseif because if the number isn't 40 or under, then by definition it has to be over 40.

I cannot understand this at all and am surprised as to how the code has passed the test.

Me too, it fails in a bunch of ways, most obviously at numbers which equal 40 or at the logic being "numbers up to and including 20" and then "numbers above and including 30" which are different. If the test tried numbers which matched those boundaries (which a test should do) then it'd fail. I've fixed that for the purposes of simplifying it, but it does mean that my code will give different results.

There's nothing in the requirements for surcharges over 3, but the example code goes up to 5. It's not clear whether this is supposed to be a surcharge of 10% of the multiple of ten below the number or what. That's the problem with requirements!

If we were to assume the pattern continued infinitely, we could probably do surcharge = Math.floor((amount - 1) / 10) + 1 and leave it at that.