forked from urfu-2016/javascript-task-3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobbery.js
More file actions
236 lines (190 loc) · 6.65 KB
/
robbery.js
File metadata and controls
236 lines (190 loc) · 6.65 KB
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
'use strict';
/**
* Сделано задание на звездочку
* Реализовано оба метода и tryLater
*/
exports.isStar = false;
var MINUTES_IN_HOUR = 60;
var MINUTES_IN_DAY = MINUTES_IN_HOUR * 24;
var WEEKDAYS = ['ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ', 'ВС'];
var ROBBERY_DAYS_COUNT = 3;
/**
* @param {Object} schedule – Расписание Банды
* @param {Number} duration - Время на ограбление в минутах
* @param {Object} workingHours – Время работы банка
* @param {String} workingHours.from – Время открытия, например, "10:00+5"
* @param {String} workingHours.to – Время закрытия, например, "18:00+5"
* @returns {Object}
*/
exports.getAppropriateMoment = function (schedule, duration, workingHours) {
var bankSchedule = getScheduleInMinutesForBank(workingHours);
var commonSchedule = getCommonSchedule(schedule, bankSchedule[0].timeZone);
var freeTimeIntervals = findFreeTime(commonSchedule);
var robberyIntervals = intersect(freeTimeIntervals, bankSchedule);
var moment = getRobberyMomentTime(robberyIntervals, duration);
return {
/**
* Найдено ли время
* @returns {Boolean}
*/
exists: function () {
return moment !== null;
},
/**
* Возвращает отформатированную строку с часами для ограбления
* Например,
* "Начинаем в %HH:%MM (%DD)" -> "Начинаем в 14:59 (СР)"
* @param {String} template
* @returns {String}
*/
format: function (template) {
if (!this.exists()) {
return '';
}
var formattedTime = getDateFromMinutes(moment.from);
return template.replace('%HH', formattedTime.hours)
.replace('%MM', formattedTime.minutes)
.replace('%DD', formattedTime.day);
},
/**
* Попробовать найти часы для ограбления позже [*]
* @star
* @returns {Boolean}
*/
tryLater: function () {
return false;
}
};
};
function getIntervalInMinutes(interval, timeZone) {
return {
from: getMinutes(interval.from, timeZone),
to: getMinutes(interval.to, timeZone)
};
}
function getMinutes(str, timeZone) {
var separators = /[ :+]/;
var data = str.split(separators);
var timeInMinutes = parseInt(data[1], 10) * MINUTES_IN_HOUR + parseInt(data[2], 10) +
(parseInt(timeZone, 10) - parseInt(data[3], 10)) * MINUTES_IN_HOUR;
return MINUTES_IN_DAY * WEEKDAYS.indexOf(data[0]) + timeInMinutes;
}
function getScheduleInMinutesForBank(workingHours) {
var from = workingHours.from.split(/[:+]/);
var to = workingHours.to.split(/[:+]/);
var schedule = [];
var minutesFrom = parseInt(from[0], 10) * MINUTES_IN_HOUR + parseInt(from[1], 10);
var minutesTo = parseInt(to[0], 10) * MINUTES_IN_HOUR + parseInt(to[1], 10);
for (var i = 0; i < 3; i++) {
schedule.push({
from: minutesFrom + MINUTES_IN_DAY * i,
to: minutesTo + MINUTES_IN_DAY * i,
timeZone: from[2]
});
}
return schedule;
}
function splitSchedule(schedule) {
var firstInterval = {
from: 0,
to: schedule[0].from
};
var secondInterval = {
from: schedule[0].to,
to: MINUTES_IN_DAY * ROBBERY_DAYS_COUNT
};
return [firstInterval, secondInterval];
}
function findFreeTime(schedule) {
var freeTimeIntervals = splitSchedule(schedule);
schedule.forEach(function (interval) {
var last = freeTimeIntervals.length - 1;
var elem = freeTimeIntervals[last];
if (interval.to <= elem.from) {
return;
}
// Интервалы пересекаются
if ((interval.from <= elem.from) && (elem.from < interval.to)) {
freeTimeIntervals[last] = {
from: interval.to,
to: MINUTES_IN_DAY * ROBBERY_DAYS_COUNT
};
return;
}
// Один внутри другого
if (interval.from >= elem.from) {
freeTimeIntervals[last] = {
from: elem.from,
to: interval.from
};
freeTimeIntervals.push({
from: interval.to,
to: MINUTES_IN_DAY * ROBBERY_DAYS_COUNT
});
}
});
return freeTimeIntervals;
}
function getCommonSchedule(gangSchedule, timeZone) {
var commonSchedule = [];
Object.keys(gangSchedule).forEach(function (name) {
commonSchedule = commonSchedule.concat(gangSchedule[name]
.map(function (interval) {
return getIntervalInMinutes(interval, timeZone);
}));
});
commonSchedule.sort(compare);
return commonSchedule;
}
function intersectIntervals(bankTime, freeTime) {
var result = {};
var isBankStartAfter = freeTime.to < bankTime.from;
var isBankEndBefore = bankTime.to < freeTime.from;
// если есть пересечение
if (!(isBankStartAfter || isBankEndBefore)) {
result = {
from: Math.max(bankTime.from, freeTime.from),
to: Math.min(bankTime.to, freeTime.to)
};
}
return result;
}
function intersect(freeTime, bankTime) {
var result = [];
bankTime.forEach(function (bankInterval) {
var intervals = freeTime.map(function (freeTimeInterval) {
return intersectIntervals(bankInterval, freeTimeInterval);
});
result = result.concat(intervals);
});
return result;
}
function isEnoughForRobbery(interval, duration) {
return interval.to - interval.from >= duration;
}
function getRobberyMomentTime(availableIntervals, duration) {
for (var i = 0; i < availableIntervals.length; i++) {
if (isEnoughForRobbery(availableIntervals[i], duration)) {
return availableIntervals[i];
}
}
return null;
}
function compare(first, second) {
return Math.sign(first.from - second.from);
}
function getDateFromMinutes(minutes) {
var dayNumber = Math.floor(minutes / MINUTES_IN_DAY);
var day = WEEKDAYS[dayNumber];
minutes = minutes - dayNumber * MINUTES_IN_DAY;
var hours = Math.floor(minutes / MINUTES_IN_HOUR);
minutes = minutes - hours * MINUTES_IN_HOUR;
return {
day: day,
hours: formatTime(hours),
minutes: formatTime(minutes)
};
}
function formatTime(time) {
return time >= 10 ? time : '0' + time;
}