From df3e15894199e68854ddf1a2aec5873eece8d7b7 Mon Sep 17 00:00:00 2001 From: "Laura \"Missha\" Vara" <152572519+vara-co@users.noreply.github.com> Date: Tue, 29 Oct 2024 20:06:14 -0600 Subject: [PATCH] Updated Pay Function Now it should display negative when money is still owed. --- starter/src/assets/script.js | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/starter/src/assets/script.js b/starter/src/assets/script.js index f7264d67..20ccda89 100644 --- a/starter/src/assets/script.js +++ b/starter/src/assets/script.js @@ -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; }