UNPKG

2.98 kBJavaScriptView Raw
1import { dateLib as defaultDateLib } from "../lib/index.js";
2/**
3 * Add a day to an existing range.
4 *
5 * The returned range takes in account the `undefined` values and if the added
6 * day is already present in the range.
7 *
8 * @group Utilities
9 */
10export function addToRange(
11/** The date to add to the range. */
12date,
13/** The range where to add `date`. */
14initialRange, min = 0, max = 0, required = false,
15/** @ignore */
16dateLib = defaultDateLib) {
17 const { from, to } = initialRange || {};
18 const { isSameDay, isAfter, isBefore } = dateLib;
19 let range;
20 if (!from && !to) {
21 // the range is empty, add the date
22 range = { from: date, to: min > 0 ? undefined : date };
23 }
24 else if (from && !to) {
25 // adding date to an incomplete range
26 if (isSameDay(from, date)) {
27 // adding a date equal to the start of the range
28 if (required) {
29 range = { from, to: undefined };
30 }
31 else {
32 range = undefined;
33 }
34 }
35 else if (isBefore(date, from)) {
36 // adding a date before the start of the range
37 range = { from: date, to: from };
38 }
39 else {
40 // adding a date after the start of the range
41 range = { from, to: date };
42 }
43 }
44 else if (from && to) {
45 // adding date to a complete range
46 if (isSameDay(from, date) && isSameDay(to, date)) {
47 // adding a date that is equal to both start and end of the range
48 if (required) {
49 range = { from, to };
50 }
51 else {
52 range = undefined;
53 }
54 }
55 else if (isSameDay(from, date)) {
56 // adding a date equal to the the start of the range
57 range = { from, to: min > 0 ? undefined : date };
58 }
59 else if (isSameDay(to, date)) {
60 // adding a dare equal to the end of the range
61 range = { from: date, to: min > 0 ? undefined : date };
62 }
63 else if (isBefore(date, from)) {
64 // adding a date before the start of the range
65 range = { from: date, to: to };
66 }
67 else if (isAfter(date, from)) {
68 // adding a date after the start of the range
69 range = { from, to: date };
70 }
71 else if (isAfter(date, to)) {
72 // adding a date after the end of the range
73 range = { from, to: date };
74 }
75 else {
76 throw new Error("Invalid range");
77 }
78 }
79 // check for min / max
80 if (range?.from && range?.to) {
81 const diff = dateLib.differenceInCalendarDays(range.to, range.from);
82 if (max > 0 && diff > max) {
83 range = { from: date, to: undefined };
84 }
85 else if (min > 1 && diff < min) {
86 range = { from: date, to: undefined };
87 }
88 }
89 return range;
90}
91//# sourceMappingURL=addToRange.js.map
\No newline at end of file