Hi,
I am stuck trying to understand a Javascript solution. Please can you help dumb it down for me if possible:
Question:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.
Example: addWithSurcharge(10, 30) should return 44.
Answer:
function addWithSurcharge (a,b) {
let sum = a + b;
if ( sum < 10) {
return sum += 2}
else if (sum > 10 && sum <= 20) {
return sum += 2}
else if (sum > 20 && sum < 30) {
return sum += 3}
else if (sum >= 30 && sum < 40) {
return sum += 4}
else if (sum > 40) {
return sum += 5}
};
————————————————————————-
I simply do not understand why this works.
FYI: I am a beginner
Thanks in advance
Try it out in your head or on a piece of paper.
This is a teaching question, and I think it's prompting you to make another function for surcharges, like this:
That's clearer what's going on, right? You can walk through it with random numbers like 10 and 30 and see it returns
10 + 1 + 30 + 3
which is the44
you wanted.I'll format the function you listed here to make things easier to read):
This function is doing the same thing, and the way to figure it out is to mentally (or pen-and paperly) walk through it with numbers that are at the extreme edges of any bounds. What do I mean by that?
Well, we know that your provided example parameters,
10, 30
will add up to40
and can see where40
goes in your function... and it doesn't go anywhere. The last two conditions are checking whether the sum is less than 40 or is greater than 40 and so none of theif
conditions match. It'll returnundefined
(I think).If we take the target sum to be in the range 20-30 (picked at random) and walk through the function with numbers that should add up to that, we can try it with
0, 20
and11, 9
. You'll see, by playing around, that you can't choose two numbers over 10 that'll add up to anything below 20. If one's over 10, the other has to be under.And that's what the example you gave is using for its logic. It's difficult to read partly because of the fact that it's testing against values which aren't the same as the ones given in the function arguments, so while working through it you have to keep mentally jumping back up to the top of the function.