Bug repair / quantity

The price was right. The count was not.

A fictional cart total ignores every item quantity. Follow the repair, then use the local calculator to see the exact difference between the original and corrected functions.

Before and after

One multiplication restores the total.

The “before” file is intentionally preserved. The “after” file validates every item before calculating its contribution.

before.js

Defective
export function totalCents(items) { return items.reduce((sum, item) => sum + Math.round(item.price * 100), 0); }

after.js

Repaired
export function totalCents(items) {
  return items.reduce((sum, item) => {
    if (item === null || typeof item !== "object") {
      throw new TypeError("Each item must be an object.");
    }

    if (!Number.isInteger(item.quantity) || item.quantity < 0) {
      throw new RangeError("Quantity must be a non-negative integer.");
    }

    if (typeof item.price !== "number" || !Number.isFinite(item.price) || item.price < 0) {
      throw new RangeError("Price must be a finite, non-negative number.");
    }

    return sum + Math.round(item.price * 100) * item.quantity;
  }, 0);
}

Working local demo

Run the same cart through both functions.

Everything stays in this page. Adding or removing demo items changes the before total without quantity, while the repaired total includes it.

Add a cart item

Demo cart

0 items

Items currently in the demo cart
ItemUnit priceQuantityLine totalRemove
Before fix$0.00
After fix$0.00
Quantity impact$0.00