UNPKG

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