Skip to content
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
8 changes: 8 additions & 0 deletions src/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ export function totalItems(items) {
return total;
}

/** Return the average price per unit across the given items. */
export function averageUnitPrice(items) {
if (items.length === 0) {
throw new RangeError('items must not be empty');
}
return totalItems(items) / items.length;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: the function is documented as the average price per unit, but it divides the line-total sum by items.length (number of line items), not by the total quantity of units. totalItems returns Σ price × quantity, so the matching divisor is Σ quantity.

Example: [{price: 10, quantity: 3}] gives 30 / 1 = 30, but the average unit price is 10. With [{price: 10, quantity: 1}, {price: 20, quantity: 3}] it returns 35, not 17.5.

The empty check has the same problem: items with all-zero quantities pass it and then divide by zero, returning NaN.

Suggested fix: sum item.quantity across items, guard on that total being 0, and divide by it.

Fix this →

}

/** Apply a percentage discount to an amount. */
export function applyDiscount(amount, percent) {
if (percent < 0 || percent > 100) {
Expand Down
Loading