(date: CalendarDate, amount: number, unit: string, preserveDate = true, minDate?: CalendarDate, maxDate?: CalendarDate)
| 12 | * @param maxDate maximum date to enforce |
| 13 | */ |
| 14 | const modifyDateBy = (date: CalendarDate, amount: number, unit: string, preserveDate = true, minDate?: CalendarDate, maxDate?: CalendarDate) => { |
| 15 | const newDate = new CalendarDate(date); |
| 16 | |
| 17 | switch (unit) { |
| 18 | case "day": |
| 19 | newDate.setDate(date.getDate() + amount); |
| 20 | break; |
| 21 | case "month": |
| 22 | if (preserveDate) { |
| 23 | newDate.setMonth(date.getMonth() + amount); |
| 24 | const stillSameMonth = amount === -1 && newDate.getMonth() === date.getMonth(); // f.e. PageUp remained in the same month |
| 25 | const monthSkipped = amount === 1 && newDate.getMonth() - date.getMonth() > 1; // f.e. PageDown skipped a whole month |
| 26 | if (stillSameMonth || monthSkipped) { // Select the last day of the month in any of these 2 scenarios |
| 27 | newDate.setDate(0); |
| 28 | } |
| 29 | } else { |
| 30 | if (amount === 1) { |
| 31 | newDate.setMonth(newDate.getMonth() + 1, 1); |
| 32 | } |
| 33 | if (amount === -1) { |
| 34 | newDate.setDate(0); |
| 35 | } |
| 36 | } |
| 37 | break; |
| 38 | case "year": |
| 39 | newDate.setYear(date.getYear() + amount); |
| 40 | if (newDate.getMonth() !== date.getMonth()) { // f.e. 29th Feb to next/prev year |
| 41 | newDate.setDate(0); // Select the last day of the month |
| 42 | } |
| 43 | break; |
| 44 | default: |
| 45 | break; |
| 46 | } |
| 47 | |
| 48 | if (minDate && newDate.isBefore(minDate)) { |
| 49 | return new CalendarDate(minDate); |
| 50 | } |
| 51 | |
| 52 | if (maxDate && newDate.isAfter(maxDate)) { |
| 53 | return new CalendarDate(maxDate); |
| 54 | } |
| 55 | |
| 56 | return newDate; |
| 57 | }; |
| 58 | |
| 59 | export default modifyDateBy; |
no test coverage detected
searching dependent graphs…