I am stuck trying to understand a Javascript solution.
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.
I simply do not understand why this works.
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.
Please can you help dumb it down for me if possible. Thank you in advance.
What I have tried:
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}
}