@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.
52 lines (50 loc) • 2.6 kB
JavaScript
import { advanceToWeekday } from "../../internal/advanceToWeekday.js";
import { booleanOption } from "../../internal/typedOptions.js";
import { plainDateOf } from "../../internal/inputChecks.js";
import { isOptionsArgument } from "../../internal/isObject.js";
import { isValidDayOfWeek } from "../../internal/isValidDayOfWeek.js";
// src/plain/calculate/previousWeekday.ts
/**
* Return a PlainDate ISO string for the previous occurrence of `dayOfWeek` before `value` (or on
* it, with `inclusive: true`).
*
* - `dayOfWeek` uses Temporal's ISO numbering: 1 (Monday) through 7 (Sunday), consistent with
* `getDayOfWeek`/`parseDayOfWeekFromDate`.
* - Returns "" on invalid input.
*
* Migrating from date-fns: its eight `previous*` functions map to one parameterized call.
* date-fns numbers days 0 (Sunday) to 6 (Saturday), so `previousDay`'s 0 becomes 7.
*
* | date-fns | gmt |
* | ------------------- | ----------------------------------------- |
* | `previousMonday` | `previousWeekday(value, 1)` |
* | `previousTuesday` | `previousWeekday(value, 2)` |
* | `previousWednesday` | `previousWeekday(value, 3)` |
* | `previousThursday` | `previousWeekday(value, 4)` |
* | `previousFriday` | `previousWeekday(value, 5)` |
* | `previousSaturday` | `previousWeekday(value, 6)` |
* | `previousSunday` | `previousWeekday(value, 7)` |
* | `previousDay(v, n)` | `previousWeekday(value, n === 0 ? 7 : n)` |
*
* @param value ISO PlainDate string
* @param dayOfWeek target ISO day of week (1-7, Monday-Sunday)
* @param options Whether `value` itself can be the result
* @returns ISO PlainDate string for the previous occurrence of `dayOfWeek`, or "" on invalid input
*
* @example previousWeekday("2024-03-15", 5) // "2024-03-08" (2024-03-15 is already a Friday, so it goes back a full week)
* @example previousWeekday("2024-03-15", 5, { inclusive: true }) // "2024-03-15"
* @example previousWeekday("2024-03-13", 5) // "2024-03-08" (Wednesday -> previous Friday)
* @example previousWeekday("invalid", 5) // ""
* @example previousWeekday("2024-03-15", 0) // "" (dayOfWeek out of range)
*/
function previousWeekday(value, dayOfWeek, options) {
if (!isOptionsArgument(options)) return "";
const date = plainDateOf(value);
if (date === null || !isValidDayOfWeek(dayOfWeek)) return "";
try {
return advanceToWeekday(date, dayOfWeek, -1, booleanOption(options?.inclusive, false)).toString();
} catch {
return "";
}
}
export { previousWeekday };