@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
22 lines (21 loc) • 836 B
JavaScript
// src/internal/advanceToWeekday.ts
/**
* Return the PlainDate for the next/previous occurrence of `dayOfWeek` relative to `date`.
*
* @param date starting PlainDate
* @param dayOfWeek target ISO day of week (1-7)
* @param direction 1 to search forward (next), -1 to search backward (previous)
* @param inclusive when `date` already falls on `dayOfWeek`, return it as-is instead of
* advancing a full week
* @returns PlainDate for the resolved weekday
*/
function advanceToWeekday(date, dayOfWeek, direction, inclusive) {
const current = date.dayOfWeek;
if (current === dayOfWeek) {
if (inclusive) return date;
return date.add({ days: 7 * direction });
}
const diff = direction === 1 ? (dayOfWeek - current + 7) % 7 : (current - dayOfWeek + 7) % 7;
return date.add({ days: diff * direction });
}
export { advanceToWeekday };