Functional Weave
Code in Python

dates.overlap@1.0.0

impl/typescript.ts

917 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { epochDayFromIso } from "./dates_add_days.ts";  ← from dates.add-days ^1.0.0 · built alongside by fune

/**
 * Days two ranges have in common. `endInclusive` says whether each end date is
 * the range's last day (a statement period) or the day after it (a half-open
 * range, a hotel stay); both ranges use the same convention.
 */
export function overlapDays(aStart: string, aEnd: string, bStart: string, bEnd: string, endInclusive: boolean): number {
  const a0 = epochDayFromIso(aStart);
  const a1 = epochDayFromIso(aEnd);
  const b0 = epochDayFromIso(bStart);
  const b1 = epochDayFromIso(bEnd);
  if (a1 < a0) throw new RangeError(`range A starts ${aStart}, after its end ${aEnd}`);
  if (b1 < b0) throw new RangeError(`range B starts ${bStart}, after its end ${bEnd}`);
  // An inclusive end is the half-open end one day later.
  const extra = endInclusive ? 1 : 0;
  const days = Math.min(a1, b1) + extra - Math.max(a0, b0);
  return days > 0 ? days : 0;
}