mirror of
https://github.com/mblanke/holiday-travel-app.git
synced 2026-03-01 05:20:22 -05:00
27 lines
1.1 KiB
TypeScript
27 lines
1.1 KiB
TypeScript
import { addDays, differenceInDays, parseISO, format, isBefore } from "date-fns";
|
|
|
|
export function enumerateDatePairs(startISO: string, endISO: string, minNights: number, maxNights: number, maxPairs = 8) {
|
|
const start = parseISO(startISO);
|
|
const end = parseISO(endISO);
|
|
const pairs: {out: string, back: string, nights: number}[] = [];
|
|
let cursor = start;
|
|
while (!isBefore(end, cursor) && pairs.length < maxPairs) {
|
|
for (let n = minNights; n <= maxNights && pairs.length < maxPairs; n++) {
|
|
const back = addDays(cursor, n);
|
|
if (isBefore(end, back)) continue;
|
|
pairs.push({ out: format(cursor, "yyyyMMdd"), back: format(back, "yyyyMMdd"), nights: n });
|
|
}
|
|
cursor = addDays(cursor, Math.max(1, Math.floor((differenceInDays(end, start) || 1) / (maxPairs))));
|
|
}
|
|
if (pairs.length === 0) {
|
|
// fallback to exact minNights from start
|
|
const back = addDays(start, minNights);
|
|
pairs.push({ out: format(start, "yyyyMMdd"), back: format(back, "yyyyMMdd"), nights: minNights });
|
|
}
|
|
return pairs;
|
|
}
|
|
|
|
export function isoToSkyscanner(iso: string) {
|
|
return iso.replace(/-/g, "");
|
|
}
|