Problems › JavaScript › billing
Apply credits to an invoice
Customer credits are applied against an invoice in order. Return the remaining unpaid balance.
- Apply credits in list order, each subtracting from the running balance.
- The balance is clamped at 0 — credits never produce a negative result.
creditFirst(invoiceTotal: int, credits: list<Credit>) → int
Where you start
function creditFirst(invoiceTotal, credits) {
}
Worked examples
| Call | Result |
|---|---|
creditFirst(10000, [{"amount":3000},{"amount":5000}]) | 2000 |
creditFirst(5000, [{"amount":3000}]) | 2000 |
creditFirst(2000, [{"amount":5000}]) | 0 |
creditFirst(0, [{"amount":1000}]) | 0 |
Hint
Walk the credits, subtract each, and clamp at each step.
Reference solution in JavaScript
function creditFirst(invoiceTotal, credits) {
let balance = invoiceTotal;
for (const c of credits) { balance -= c.amount; if (balance < 0) balance = 0; }
return balance;
}