Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor functions in cart.js #33

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions js/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,18 @@ const removeFromCart = (productId) => {
return;
};

/**
* Formats a numeric price as USD currency.
* @param {number} price - The numeric price to be formatted.
* @returns {string} The formatted price in USD currency format.
*/
const formatPriceAsUSD = (price) => {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(price);
};

/**
* Calculates and displays the total price and quantity of items in the cart.
* The total price is formatted as a currency value in US dollars, and the
Expand All @@ -120,10 +132,7 @@ const calculateTotal = () => {
return total + item.price * item.qtyInCart;
}, 0);

totalPriceEl.textContent = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(totalPrice);
totalPriceEl.textContent = formatPriceAsUSD(totalPrice);

totalQuantity === 1
? (productQuantity.textContent = `${totalQuantity} product`)
Expand Down Expand Up @@ -154,10 +163,7 @@ const displayCartProducts = () => {
imgContainer.appendChild(itemImg);

const itemPrice = createElementWithClass("p", "cart-item-price");
itemPrice.textContent = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(price * qtyInCart);
itemPrice.textContent = formatPriceAsUSD(price * qtyInCart);

const itemQtyWrapper = createElementWithClass("div", "item-qty-wrapper");
const decrementBtn = createButton(
Expand Down