UNPKG

2.37 kBPlain TextView Raw
1import type { DateLib, Matcher } from "../types/index.js";
2
3import { rangeIncludesDate } from "./rangeIncludesDate.js";
4import {
5 isDateAfterType,
6 isDateBeforeType,
7 isDateInterval,
8 isDateRange,
9 isDatesArray,
10 isDayOfWeekType
11} from "./typeguards.js";
12
13/**
14 * Returns whether a day matches against at least one of the given
15 * {@link Matcher}.
16 *
17 * ```tsx
18 * const day = new Date(2022, 5, 19);
19 * const matcher1: DateRange = {
20 * from: new Date(2021, 12, 21),
21 * to: new Date(2021, 12, 30)
22 * }
23 * const matcher2: DateRange = {
24 * from: new Date(2022, 5, 1),
25 * to: new Date(2022, 5, 23)
26 * }
27 * const isMatch(day, [matcher1, matcher2]); // true, since day is in the matcher1 range.
28 * ```
29 *
30 * @group Utilities
31 */
32export function dateMatchModifiers(
33 date: Date,
34 matchers: Matcher | Matcher[],
35 dateLib: DateLib
36): boolean {
37 const matchersArr = !Array.isArray(matchers) ? [matchers] : matchers;
38 const { isSameDay, differenceInCalendarDays, isAfter } = dateLib;
39 return matchersArr.some((matcher: Matcher) => {
40 if (typeof matcher === "boolean") {
41 return matcher;
42 }
43 if (dateLib.isDate(matcher)) {
44 return isSameDay(date, matcher);
45 }
46 if (isDatesArray(matcher, dateLib)) {
47 return matcher.includes(date);
48 }
49 if (isDateRange(matcher)) {
50 return rangeIncludesDate(matcher, date, false, dateLib);
51 }
52 if (isDayOfWeekType(matcher)) {
53 if (!Array.isArray(matcher.dayOfWeek)) {
54 return matcher.dayOfWeek === date.getDay();
55 }
56 return matcher.dayOfWeek.includes(date.getDay());
57 }
58 if (isDateInterval(matcher)) {
59 const diffBefore = differenceInCalendarDays(matcher.before, date);
60 const diffAfter = differenceInCalendarDays(matcher.after, date);
61 const isDayBefore = diffBefore > 0;
62 const isDayAfter = diffAfter < 0;
63 const isClosedInterval = isAfter(matcher.before, matcher.after);
64 if (isClosedInterval) {
65 return isDayAfter && isDayBefore;
66 } else {
67 return isDayBefore || isDayAfter;
68 }
69 }
70 if (isDateAfterType(matcher)) {
71 return differenceInCalendarDays(date, matcher.after) > 0;
72 }
73 if (isDateBeforeType(matcher)) {
74 return differenceInCalendarDays(matcher.before, date) > 0;
75 }
76 if (typeof matcher === "function") {
77 return matcher(date);
78 }
79 return false;
80 });
81}