diff --git a/src/schedule.js b/src/schedule.js index 862dc55..f05cf46 100644 --- a/src/schedule.js +++ b/src/schedule.js @@ -23,5 +23,61 @@ * calendar date in 'YYYY-MM-DD' form. */ export function billingDates(start, rule) { - throw new Error('not implemented'); + if (rule === null || typeof rule !== 'object') { + throw new RangeError('rule is required'); + } + const { every, until } = rule; + const interval = rule.interval === undefined ? 1 : rule.interval; + const count = rule.count; + const skip = new Set(rule.skip === undefined ? [] : rule.skip); + + 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 results = []; + for (let i = 0; count === undefined || results.length < count; i++) { + let date; + if (every === 'week') { + date = formatDate(new Date(Date.UTC(y, m - 1, d + 7 * interval * i))); + } else { + const total = m - 1 + interval * i; + 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 (!skip.has(date)) results.push(date); + } + return results; +} + +function parseDate(str, name) { + const match = typeof str === 'string' && /^(\d{4})-(\d{2})-(\d{2})$/.exec(str); + if (match) { + const [y, m, d] = [Number(match[1]), Number(match[2]), Number(match[3])]; + 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 date in YYYY-MM-DD form`); +} + +function formatDate(dt) { + const p = (n, w) => String(n).padStart(w, '0'); + return `${p(dt.getUTCFullYear(), 4)}-${p(dt.getUTCMonth() + 1, 2)}-${p(dt.getUTCDate(), 2)}`; }