1 | import type { DateLib, Matcher } from "../types/index.js";
|
2 |
|
3 | import { rangeIncludesDate } from "./rangeIncludesDate.js";
|
4 | import {
|
5 | isDateAfterType,
|
6 | isDateBeforeType,
|
7 | isDateInterval,
|
8 | isDateRange,
|
9 | isDatesArray,
|
10 | isDayOfWeekType
|
11 | } from "./typeguards.js";
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | export 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 | }
|