Skip to content

Commit

Permalink
Updated Pay Function
Browse files Browse the repository at this point in the history
Now it should display negative when money is still owed.
  • Loading branch information
vara-co authored Oct 30, 2024
1 parent 61f30f7 commit df3e158
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions starter/src/assets/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,38 @@ function emptyCart() {

// Function PAY taking amount as an argument.
// This will determine the difference that needs to be returned to the shopper, or if they still owe

// Variable to track total payment
let totalPaid = 0;

function pay(amount) {
// total price in cart
// Avoiding accepting negative amounts or zero
if (amount <= 0) {
return "Invalid payment.";
}

// Add amount to total amount paid
totalPaid += amount;

// Total in cart
const ttlCost = cartTotal();

// checking balance
const balance = amount - ttlCost;
// Remaining balance calculation
const remaining = totalPaid - ttlCost;

// Conditional
if (remaining < 0) {
return remaining;
} else {
const change = remaining;
totalPaid = 0;
emptyCart(); // Clear cart when payment completed

// Find out the change if any
return change

}

// if balance positive, give change. If balance negative, needs to pay.
return balance;
}


Expand Down

0 comments on commit df3e158

Please sign in to comment.