diff --git a/src/schedule.js b/src/schedule.js index 862dc55..5fde74f 100644 --- a/src/schedule.js +++ b/src/schedule.js @@ -23,5 +23,57 @@ * 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 [y, m, d] = parseDate(start, 'start'); + if (until !== undefined) parseDate(until, 'until'); + const skipped = new Set(skip); + + const result = []; + for (let k = 0; ; k++) { + let date; + if (every === 'week') { + date = formatDate(new Date(Date.UTC(y, m - 1, d + 7 * interval * k))); + } else { + const total = m - 1 + interval * k; + const year = y + Math.floor(total / 12); + const month = total % 12; + const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); + date = formatDate(new Date(Date.UTC(year, month, Math.min(d, lastDay)))); + } + if (until !== undefined && date > until) break; + if (skipped.has(date)) continue; + result.push(date); + if (count !== undefined && result.length >= count) break; + } + return result; +} + +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); + const dt = new Date(Date.UTC(y, m - 1, d)); + dt.setUTCFullYear(y); + if (dt.getUTCFullYear() === y && dt.getUTCMonth() === m - 1 && dt.getUTCDate() === d) { + return [y, m, d]; + } + } + throw new RangeError(`${name} must be a real calendar date in YYYY-MM-DD form`); +} + +function formatDate(dt) { + return dt.toISOString().slice(0, 10); }