12. Buy-Now-Pay-Later Installment Schedule

MediumJavaScriptPayments

A checkout offers "Pay in 3 or 6 monthly installments". The schedule shown before purchase must match the one the finance system charges later, to the piaster and to the day.

Two bugs reached production at another company: a customer whose first payment was on 31 January got a second due date of 3 March (JavaScript date overflow), and the installments added up to one piaster less than the order total.

Your task: - addMonths(date, months): the date months months after date, both as "YYYY-MM-DD". - buildInstallmentPlan(total, count, firstDueDate): returns [{ number, dueDate, amount }], using addMonths.

Rules: - addMonths keeps the same day of the month. If the target month is shorter, use its last day. 31 Jan + 1 month = 28 Feb (29 Feb in a leap year). - Installment k is due addMonths(firstDueDate, k - 1). Always count from the first due date, never from the previous installment, so the day never drifts: 31 Jan, 28 Feb, 31 Mar. - amount = floor(total / count). The leftover piasters are added to the first installment. - number starts at 1.

Notes: - The helper daysInMonth(year, month) is available (month is 1 to 12). Dates are calendar dates, so you do not need time zones.

What you'll write

  • addMonthsfunctionAdds whole months to a "YYYY-MM-DD" date, clamping to the end of the month.
  • buildInstallmentPlanfunctionThe full schedule. Uses addMonths.

Each one has its own test cases, and the last one is also tested together with the others. Implement them in order.

Helpers you can use

These functions are already defined. Call them from your code; you don't need to copy them.

  • daysInMonth(year, month) → numberDays in a month, with leap years. month is 1 to 12.
Show the helper code
/** Number of days in a month. month is 1 (January) to 12 (December). */
function daysInMonth(year, month) {
  if (month === 2) {
    const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    return leap ? 29 : 28;
  }
  return [4, 6, 9, 11].includes(month) ? 30 : 31;
}

Examples

Example 1

Function
buildInstallmentPlan
Input
  • total = 10000
  • count = 3
  • firstDueDate = "2027-01-31"
Output
  • [
      { number: 1, dueDate: "2027-01-31", amount: 3334 },
      { number: 2, dueDate: "2027-02-28", amount: 3333 },
      { number: 3, dueDate: "2027-03-31", amount: 3333 }
    ]
Explanation
10000 / 3 = 3333 with 1 left over, added to the first installment. February has 28 days, and March goes back to the 31st.

Solution

Write addMonths and buildInstallmentPlan. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.

Test Results

Click "Run Code" to test your solution.