Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 59 lines · 2.2 KiB · at b0c0c21

export type DateRange = { start: string; end: string };export type RangeErrorDetails =  | { kind: "invalid_date"; index: number; value: string }  | { kind: "inverted_range"; index: number };export class DateRangeError extends Error {  public readonly kind: RangeErrorDetails["kind"];  constructor(details: RangeErrorDetails) {    super(details.kind);    this.kind = details.kind;    Object.assign(this, details);  }}const isLeap = (y: number): boolean => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;const daysIn = (y: number, m: number): number => (m === 2 ? (isLeap(y) ? 29 : 28) : [4, 6, 9, 11].includes(m) ? 30 : 31);type Ymd = { y: number; m: number; d: number };const parse = (s: unknown): Ymd | undefined => {  if (typeof s !== "string") return undefined;  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);  if (!match) return undefined;  const y = Number(match[1]);  const m = Number(match[2]);  const d = Number(match[3]);  if (m < 1 || m > 12 || d < 1 || d > daysIn(y, m)) return undefined;  return { y, m, d };};const pad = (n: number, w: number): string => String(n).padStart(w, "0");const nextDay = ({ y, m, d }: Ymd): string => {  if (d < daysIn(y, m)) return `${pad(y, 4)}-${pad(m, 2)}-${pad(d + 1, 2)}`;  if (m < 12) return `${pad(y, 4)}-${pad(m + 1, 2)}-01`;  return `${pad(y + 1, 4)}-01-01`;};/** Throws DateRangeError (constructed with the matching RangeErrorDetails). */export function mergeRanges(ranges: readonly DateRange[]): DateRange[] {  ranges.forEach((r, index) => {    if (!parse(r.start)) throw new DateRangeError({ kind: "invalid_date", index, value: r.start });    if (!parse(r.end)) throw new DateRangeError({ kind: "invalid_date", index, value: r.end });    if (r.start > r.end) throw new DateRangeError({ kind: "inverted_range", index });  });  // YYYY-MM-DD strings sort lexicographically in date order.  const sorted = ranges.map((r) => ({ start: r.start, end: r.end })).sort((a, b) => (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));  const out: DateRange[] = [];  for (const r of sorted) {    const last = out[out.length - 1];    if (last && r.start <= nextDay(parse(last.end) as Ymd)) {      if (r.end > last.end) last.end = r.end;    } else {      out.push(r);    }  }  return out;}