-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
250 lines (202 loc) · 7.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
'use strict';
const getStartDateValue = () => {
const startDate = document.getElementById('start-date');
return new Date(startDate.value);
};
const getEndDateValue = () => {
const endDate = document.getElementById('end-date');
return new Date(endDate.value);
};
const setDatesAtInputs = () => {
const startDateInput = document.getElementById('start-date');
const endDateInput = document.getElementById('end-date');
if (!startDateInput.value) {
alert("Please, choose start date!");
} else if (!endDateInput.value) {
alert("Please, choose end date!");
}
};
const removeAttrDisabled = () => {
const startDate = document.getElementById('start-date');
const endDate = document.getElementById('end-date');
const presetSelect = document.getElementById('preset-select');
const setDisabledState = (disabled) => {
endDate.disabled = disabled;
presetSelect.disabled = disabled;
};
const updateDisabledState = () => {
if (startDate.value) {
setDisabledState(false);
} else {
setDisabledState(true);
}
};
startDate.addEventListener('change', updateDisabledState);
updateDisabledState();
};
const stopChooseDatesBeforeEndDate = () => {
const startDateInput = document.getElementById('start-date');
const endDateInput = document.getElementById('end-date');
startDateInput.addEventListener('change', function() {
const startDateValue = startDateInput.value;
endDateInput.min = startDateValue;
// Перевіряємо, чи обрана дата в полі "end-date" більше за дату в полі "start-date".
// Якщо так, то оновлюємо значення поля "end-date".
if (endDateInput.value < startDateValue) {
endDateInput.value = startDateValue;
}
});
}
const addPresetSelectFunctionality = () => {
const endDateInput = document.getElementById('end-date');
const presetSelect = document.getElementById('preset-select');
presetSelect.addEventListener('change', function() {
const startDateValue = getStartDateValue();
if (startDateValue) {
const startDate = new Date(startDateValue);
let endDate;
switch (presetSelect.value) {
case 'week':
endDate = new Date(startDate.getTime() + 6 * 24 * 60 * 60 * 1000);
break;
case 'month':
endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0, 23, 59, 59, 999);
break;
default:
return;
}
const formattedEndDate = endDate.toISOString().slice(0, 10);
endDateInput.value = formattedEndDate;
}
});
};
const calculateDurationInDays = (startDate, endDate, type) => {
const oneDay = 24 * 60 * 60 * 1000;
let currentDay = new Date(startDate);
let weekdays = 0;
let weekends = 0;
while (currentDay <= endDate) {
const dayOfWeek = currentDay.getDay();
if (dayOfWeek === 0 || dayOfWeek === 6) {
weekends++;
} else {
weekdays++;
}
currentDay = new Date(currentDay.getTime() + oneDay);
}
if (type === 'weekdays') {
return weekdays;
} else if (type === 'weekends') {
return weekends;
} else if (type === 'alldays') {
return weekdays + weekends;
} else {
return 0; // Неіснуючий type
}
};
const formatDuration = (duration, type) => {
switch (type) {
case 'days':
return `${duration} days`;
case 'hours':
return `${duration * 24} hours`;
case 'minutes':
return `${duration * 24 * 60} minutes`;
case 'seconds':
return `${duration * 24 * 60 * 60} seconds`;
default:
return "Invalid dimension";
}
};
const initDurationBetweenDates = () => {
const startDateValue = getStartDateValue();
const endDateValue = getEndDateValue();
const start = new Date(startDateValue);
const end = new Date(endDateValue);
const durationTypes = ['weekdays', 'weekends', 'alldays'];
const timeTypes = ['days', 'hours', 'minutes', 'seconds'];
let result = '';
durationTypes.forEach(durationType => {
const durationCheckbox = document.getElementById(durationType);
if (durationCheckbox.checked) {
timeTypes.forEach(timeType => {
const timeCheckbox = document.getElementById(timeType);
if (timeCheckbox.checked) {
const duration = calculateDurationInDays(start, end, durationType);
const formattedDuration = formatDuration(duration, timeType);
result += `${formattedDuration}`;
}
});
}
});
document.getElementById('result-area').value = result;
};
const saveDataToLocalStorage = () => {
const startDateValue = getStartDateValue();
const endDateValue = getEndDateValue();
const resultArea = document.getElementById('result-area');
const result = resultArea.value;
if (isNaN(startDateValue.getTime()) || isNaN(endDateValue.getTime())) {
console.error('Invalid date: Please, choose both dates and type duration to save information in localStorage!');
return;
}
const startDate = startDateValue.toISOString().slice(0, 10);
const endDate = endDateValue.toISOString().slice(0, 10);
// Отримання попередньо збережених результатів з локального сховища
let savedResults = localStorage.getItem('savedResults');
if (!savedResults) {
savedResults = [];
} else {
savedResults = JSON.parse(savedResults);
}
// Додавання нового результату до списку
const newResult = {
startDate: startDate,
endDate: endDate,
result: result
};
savedResults.push(newResult);
// Збереження останніх 10 результатів у локальне сховище
if (savedResults.length > 10) {
savedResults = savedResults.slice(-10);
}
localStorage.setItem('savedResults', JSON.stringify(savedResults));
};
const renderDataFromLocalStorage = () => {
const showDataElement = document.getElementById('show-localstorage-data');
const savedResults = localStorage.getItem('savedResults');
// Перевірка, чи є збережені результати
if (savedResults) {
const resultsArray = JSON.parse(savedResults);
// Створення HTML-рядка для виведення кожного результату
const resultsHTML = resultsArray.map(result => {
return `<div class="data-output__items">
<p class="data-output__start">Start Date: ${result.startDate}</p>
<p class="data-output__end">End Date: ${result.endDate}</p>
<p class="data-output__result">Result: ${result.result}</p>
</div>`;
}).join('');
showDataElement.innerHTML = resultsHTML;
} else {
showDataElement.innerHTML = '<p>No saved results found.</p>';
}
}
const initCalculateDuration = () => {
const trigger = document.querySelector('.form-control__btn');
removeAttrDisabled();
stopChooseDatesBeforeEndDate();
addPresetSelectFunctionality();
trigger.addEventListener('click', function () {
// Перевірка, чи обрані дати
setDatesAtInputs();
// Розрахунок днів, часів, мінут, секунд
initDurationBetweenDates();
// Збереження у локальному сховищі останніх 10 результатів, які рахував юзер на сторінці в додатку
saveDataToLocalStorage();
// Виведення данних з LocalStorage на сторінку
renderDataFromLocalStorage();
});
// Виведення данних з LocalStorage на сторінку при завантаженні
renderDataFromLocalStorage();
};
initCalculateDuration();