diff --git a/src/schedule.js b/src/schedule.js index 862dc55..b9a1842 100644 --- a/src/schedule.js +++ b/src/schedule.js @@ -23,5 +23,60 @@ * calendar date in 'YYYY-MM-DD' form. */ export function billingDates(start, rule) { - throw new Error('not implemented'); + const { every, interval = 1, count, until, skip = [] } = rule ?? {}; + + if (every !== 'week' && every !== 'month') { + throw new RangeError("every must be 'week' or 'month'"); + } + if (!Number.isInteger(interval) || interval < 1) { + throw new RangeError('interval must be a positive integer'); + } + if (count !== undefined && (!Number.isInteger(count) || count < 1)) { + throw new RangeError('count must be a positive integer'); + } + if (count === undefined && until === undefined) { + throw new RangeError('count or until is required'); + } + const startParts = parseDate(start, 'start'); + if (until !== undefined) parseDate(until, 'until'); + const skipped = new Set(skip); + + const [y, m, d] = startParts; + const result = []; + for (let i = 0; count === undefined || result.length < count; i++) { + let date; + if (every === 'week') { + const t = new Date(0); + t.setUTCFullYear(y, m - 1, d + 7 * interval * i); + date = format(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate()); + } else { + const total = y * 12 + (m - 1) + interval * i; + const year = Math.floor(total / 12); + const month = (total % 12) + 1; + date = format(year, month, Math.min(d, daysInMonth(year, month))); + } + // 'YYYY-MM-DD' strings compare chronologically + if (until !== undefined && date > until) break; + if (!skipped.has(date)) result.push(date); + } + return result; +} + +function daysInMonth(year, month) { + const t = new Date(0); + t.setUTCFullYear(year, month, 0); + return t.getUTCDate(); +} + +function format(y, m, d) { + return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`; +} + +function parseDate(s, name) { + const match = typeof s === 'string' && /^(\d{4})-(\d{2})-(\d{2})$/.exec(s); + if (match) { + const [y, m, d] = match.slice(1).map(Number); + if (m >= 1 && m <= 12 && d >= 1 && d <= daysInMonth(y, m)) return [y, m, d]; + } + throw new RangeError(`${name} must be a real calendar date in YYYY-MM-DD form`); }