@e-group/material-lab
Version:
EGroup Team Lab - Incubator for EGroup Team experimental React components.
73 lines (63 loc) • 2.11 kB
JavaScript
import { startOfWeek, startOfMonth, endOfWeek, endOfMonth, isBefore, isAfter, addDays, isSameDay, isWithinInterval, toDate, isValid, isSameMonth, max, min, addMonths } from 'date-fns';
export const identity = x => x;
export const chunks = (array, size) => Array.from({
length: Math.ceil(array.length / size)
}, (v, i) => array.slice(i * size, i * size + size));
export const getDaysInMonth = 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;
}; // Date
export const getValidDate = (date, defaultValue) => {
if (date) {
const parsed = toDate(new Date(date));
if (isValid(parsed)) return parsed;
}
return defaultValue;
};
export const getValidatedMonths = (minDate, maxDate, startDate, endDate) => {
if (startDate && endDate) {
const newStart = max([startDate, minDate]);
const newEnd = min([endDate, maxDate]);
return [newStart, isSameMonth(newStart, newEnd) ? addMonths(newStart, 1) : newEnd];
}
return [startDate, endDate];
};
export const isWithinIntervalValid = (date, startDate, endDate) => {
if (startDate && endDate && isBefore(startDate, endDate)) {
return isWithinInterval(date, {
start: startDate,
end: endDate
});
}
return false;
};
export const isSameDayValid = (dateLeft, dateRight) => {
if (dateLeft && dateRight) {
return isSameDay(dateLeft, dateRight);
}
return false;
};
export const isBeforeValid = (date, dateToCompare) => {
if (date && dateToCompare) {
return isBefore(date, dateToCompare);
}
return false;
};
export const isAfterValid = (date, dateToCompare) => {
if (date && dateToCompare) {
return isAfter(date, dateToCompare);
}
return false;
};
export const inDateRange = (day, startDate, endDate) => {
if (startDate && endDate) {
return isWithinIntervalValid(day, startDate, endDate) || isSameDayValid(day, startDate) || isSameDayValid(day, endDate);
}
return false;
};