before.js
Defectiveexport function totalCents(items) { return items.reduce((sum, item) => sum + Math.round(item.price * 100), 0); }
Bug repair / quantity
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
The “before” file is intentionally preserved. The “after” file validates every item before calculating its contribution.
export function totalCents(items) { return items.reduce((sum, item) => sum + Math.round(item.price * 100), 0); }
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
Everything stays in this page. Adding or removing demo items changes the before total without quantity, while the repaired total includes it.
0 items
| Item | Unit price | Quantity | Line total | Remove |
|---|