nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
49 lines (48 loc) • 2.25 kB
JavaScript
import { isValidArray } from '../../guards/non-primitives.js';
import { isNumber } from '../../guards/primitives.js';
import { INTERNALS } from '../Chronos.js';
import { DAYS, MS_PER_DAY } from '../constants.js';
export const dateRangePlugin = ($Chronos) => {
const { internalDate: $Date, cast, withOrigin, offset } = $Chronos[INTERNALS];
$Chronos.prototype.getDatesInRange = function (options) {
let startDate = this.clone(), endDate = this.addWeeks(4);
const { format = 'local', onlyDays, skipDays, roundDate = false } = options ?? {};
if (options) {
if ('from' in options || 'to' in options) {
if (options?.from)
startDate = cast(options.from);
if (options?.to)
endDate = cast(options.to);
}
else if ('span' in options || 'unit' in options) {
const { span = 4, unit = 'week' } = options;
endDate = startDate.add(span, unit);
}
}
if (roundDate) {
startDate = startDate.startOf('day');
endDate = endDate.startOf('day');
}
const skippedDays = isValidArray(onlyDays)
? onlyDays
: isValidArray(skipDays)
? skipDays
: [];
const skipSet = new Set(skippedDays.map((day) => (isNumber(day) ? day : DAYS.indexOf(day))));
const dates = [];
const startTime = $Date(startDate).getTime();
const endTime = $Date(endDate).getTime();
const step = (startTime <= endTime ? 1 : -1) * MS_PER_DAY;
const totalDays = Math.floor(Math.abs(endTime - startTime) / MS_PER_DAY);
for (let i = 0; i <= totalDays; i++) {
const ts = startTime + i * step;
const wDay = new Date(ts).getDay();
const include = isValidArray(onlyDays) ? skipSet.has(wDay) : !skipSet.has(wDay);
if (include) {
const chr = withOrigin(new $Chronos(ts), 'clone', offset(this), startDate.timeZoneName, startDate.timeZoneId, startDate.$tzTracker);
dates.push(format === 'local' ? chr.toLocalISOString() : chr.toISOString());
}
}
return dates;
};
};