Hi coders,
I was trying this exercise but I don’t understand why give this error
addWithSurcharge(1, 1) does not return 4 , but 3 .
This is the exercise :
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 , the surcharge is 2 . The call addWithSurcharge(5, 15) should return 23 .
In this line you are first checking if amount is less than/equal to 10 or greater than 10. That will always evaluate to true since every option is true. So now we have essentially: if ((true) && (amount2 <= 10 || amount2 > 10))
Same thing for amount2. It will always be either less than//equal to 10 or greater than 10. So now it’s: if ((true) && (true))
Of course that’s always true. So return surcharge + 1; will always follow.
@camcode The function needs to return a total which includes the two amounts passed to the function as well as the surcharge for each amount.
function addWithSurcharge(amount1, amount2) {
function calcSurcharge(amount) {
if (amount <= 10) {
return 1;
} else {
return 2;
}
}
var totalAmounts = amount1 + amount2;
return totalAmounts + calcSurcharge(amount1) + calcSurcharge(amount2);
}
EDIT: I update my solution to reflect the use of if/else instead of a ternary operator, since I assume the point of the challenge was to use an if/else statement.
For each amount less than or equal to 10 , the surcharge is 1 . For each amount greater than 10 , the surcharge is 2 . The call addWithSurcharge(5, 15) should return 23 .
How do you get 23 from 5 and 15? What is the surcharge value vs the sum of the two numbers? I think that this question should help you see the error in your logic.
In general, you want to keep you logic clean and simple. Get something that works correctly and is simple first. If you want, later you can go back and try to reduce the number of lines. But simplicity and readability improves maintainability and saves you time in the future.
A function 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 , the surcharge is 2 . The call addWithSurcharge(5, 15) should return 23 .
Using the example for a result of 23:
=> 5 is less than or equal to 10, so you have to add this amount with surcharge of 1 => 5 + 1 (a)
=> 15 is greater than 10, so you have to add this amount with surcharge of 2 = > 15 + 2 (b)
I’m trying to try to consolidate the basics, but I’ve been struggling for almost two years without having great results. I do little things, but sometimes they seem difficult.