UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

53 lines (52 loc) 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dateRangePlugin = void 0; const non_primitives_1 = require("../../guards/non-primitives"); const primitives_1 = require("../../guards/primitives"); const Chronos_1 = require("../Chronos"); const constants_1 = require("../constants"); const dateRangePlugin = ($Chronos) => { const { internalDate: $Date, cast, withOrigin, offset } = $Chronos[Chronos_1.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 = (0, non_primitives_1.isValidArray)(onlyDays) ? onlyDays : (0, non_primitives_1.isValidArray)(skipDays) ? skipDays : []; const skipSet = new Set(skippedDays.map((day) => ((0, primitives_1.isNumber)(day) ? day : constants_1.DAYS.indexOf(day)))); const dates = []; const startTime = $Date(startDate).getTime(); const endTime = $Date(endDate).getTime(); const step = (startTime <= endTime ? 1 : -1) * constants_1.MS_PER_DAY; const totalDays = Math.floor(Math.abs(endTime - startTime) / constants_1.MS_PER_DAY); for (let i = 0; i <= totalDays; i++) { const ts = startTime + i * step; const wDay = new Date(ts).getDay(); const include = (0, non_primitives_1.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; }; }; exports.dateRangePlugin = dateRangePlugin;