Drill

ProblemsTypeScript › billing

Apply credits to an invoice

mediumbillingTypeScript

Customer credits are applied against an invoice in order. Return the remaining unpaid balance.

creditFirst(invoiceTotal: int, credits: list<Credit>) → int

Solve it in the editor →

Where you start

function creditFirst(invoiceTotal: number, credits: Credit[]): number {
  
}

Worked examples

CallResult
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 TypeScript
function creditFirst(invoiceTotal: number, credits: Credit[]): number {
  let balance = invoiceTotal;
  for (const c of credits) { balance -= c.amount; if (balance < 0) balance = 0; }
  return balance;
}

The same problem in another language

More billing problems in TypeScript