I’m trying to make this shop script to include these criteria’s:
Right now the balance does go under zero, and the voucher doesn’t get used... maybe it’s obvious but Im being driven insane.
Also, any tips to optimize this code?
Thank you! I’m sorry if this is painfully obvious. I’m completely new to this!
var total = 500;
var balance = 400;
var voucher = 100;
useVoucher = true;
if ( (total > balance) || (balance < 0) ) {
console.log("Insufficient funds. The total is " + total + "$ and you only have a balance of " + balance + "$.");
} else if (useVoucher = true) {
total = total - voucher
console.log(voucher + "$ Voucher applied. The new total is " + total + "$.");
} else {
console.log("You can't afford this item");
}
if ((balance - total < 0) && balance > total); {
console.log("Success! You have a new balance of " + (balance - total) + "$.");
}
First You have to check if you can use voucher. It happens if you don't have enough balance, but you have enough balance using the voucher.
In this situation use the voucher.
Than check if you have enough balance to pay or not.
Here is the code:
var total = 500;
var balance = 400;
var voucher = 100;
useVoucher = true;
if (total > balance // Not enough balance
&& useVoucher // You can use the voucher
&& total - voucher <= balance) { // Total minus voucher is under balance
console.log(voucher + "$ Voucher applied. The new total is " + total + "$.");
// IN this case use voucher
total = total - voucher;
// Would be better to check here if total is under 0,
// otherwise in the next few lines of code you will increase your balance.
}
if (total <= balance) { // Check if you have enough balance
balance = balance - total;
console.log("Success! You have a new balance of " + balance + "$.");
} else { // Not enough balance
console.log("Insufficient funds. The total is " + total + "$ and you only have a balance of " + balance + "$.");
}
An additional check should be done to check if the voucher is bigger than the total.Generally using a voucher you loose the extra money of the voucher if it is bigger than the price, but in this situation I didn't added this check because it was not explicitly requested.