DEV Community

Discussion on: Issue with Else If Statement

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.