-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathutils.ts
75 lines (63 loc) · 1.82 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {
startOfWeek,
startOfMonth,
endOfWeek,
endOfMonth,
isBefore,
addDays,
isSameDay,
isWithinInterval,
toDate,
parseISO,
isValid
} from "date-fns";
import { DateRange } from "./types";
export const identity = <T>(x: T) => x;
export const chunks = <T>(array: ReadonlyArray<T>, size: number): T[][] => {
return Array.from({ length: Math.ceil(array.length / size) }, (v, i) =>
array.slice(i * size, i * size + size)
);
};
export const combine = (...args: any[]): string => args.filter(identity).join(" ");
// Date
export const getDaysInMonth = (date: Date) => {
const startWeek = startOfWeek(startOfMonth(date));
const endWeek = endOfWeek(endOfMonth(date));
const days = [];
for (let curr = startWeek; isBefore(curr, endWeek); ) {
days.push(curr);
curr = addDays(curr, 1);
}
return days;
};
export const isStartOfRange = ({ startDate }: DateRange, day: Date) =>
(startDate && isSameDay(day, startDate)) as boolean;
export const isEndOfRange = ({ endDate }: DateRange, day: Date) =>
(endDate && isSameDay(day, endDate)) as boolean;
export const inDateRange = ({ startDate, endDate }: DateRange, day: Date) =>
(startDate &&
endDate &&
(isWithinInterval(day, {
start: startDate,
end: endDate
}) ||
isSameDay(day, startDate) ||
isSameDay(day, endDate))) as boolean;
export const isRangeSameDay = ({ startDate, endDate }: DateRange) => {
if (startDate && endDate) {
return isSameDay(startDate, endDate);
}
return false;
};
type Falsy = false | null | undefined | 0 | "";
export const parseOptionalDate = (date: Date | string | Falsy, defaultValue: Date) => {
if (date instanceof Date) {
const parsed = toDate(date);
if (isValid(parsed)) return parsed;
}
if (date instanceof String) {
const parsed = parseISO(date as string);
if (isValid(parsed)) return parsed;
}
return defaultValue;
};