-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathrobbery.js
More file actions
279 lines (249 loc) · 9.56 KB
/
robbery.js
File metadata and controls
279 lines (249 loc) · 9.56 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
'use strict';
/**
* Сделано задание на звездочку
* Реализовано оба метода и tryLater
*/
exports.isStar = true;
/**
* @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 timeZone = parseInt(workingHours.from.split('+')[1]);
var convertedSchedule = convertIntervals(
getCommonSchedule(schedule), timeZone);
var convertedWorkingHours = convertIntervals(
getIntervals(workingHours), timeZone);
return {
possibleIntervals: getPossibleIntervals(
convertedWorkingHours, convertedSchedule),
duration: duration,
robberyTime: undefined,
/**
* Находит время, не раньше переданного
* @param {Date} lower - Нижняя граница времени
* @param {Date} upper - Верхняя граница времени
* @returns {Date} Подходящее время
*/
findWithin: function (lower, upper) {
var appropriateTimes = [];
var robberyDuration = this.duration;
this.possibleIntervals.forEach(function (interval) {
if (lower > interval.from) {
interval.from = lower;
}
if (upper < interval.to) {
interval.to = upper;
}
if (interval.to > interval.from &&
new Date(interval.to - interval.from) >=
new Date(1000 * 60 * robberyDuration)) {
appropriateTimes.push(interval.from);
}
});
appropriateTimes.sort();
return appropriateTimes[0];
},
/**
* Найдено ли время
* @returns {Boolean}
*/
exists: function () {
var appropriateTime = this.findWithin(
new Date(2016, 9, 24, 5),
new Date(2016, 9, 26, 28, 59, 59));
if (typeof appropriateTime !== 'undefined') {
this.robberyTime = appropriateTime;
return true;
}
return false;
},
/**
* Возвращает отформатированную строку с часами для ограбления
* Например,
* "Начинаем в %HH:%MM (%DD)" -> "Начинаем в 14:59 (СР)"
* @param {String} template
* @returns {String}
*/
format: function (template) {
return typeof this.robberyTime === 'undefined' &&
!this.exists() ? '' : formatTime(this.robberyTime, template);
},
/**
* Попробовать найти часы для ограбления позже [*]
* @star
* @returns {Boolean}
*/
tryLater: function () {
if (typeof this.robberyTime === 'undefined') {
this.exists();
}
if (typeof this.robberyTime === 'undefined' ||
this.robberyTime < new Date(2016, 9, 24, 5) ||
this.robberyTime > new Date(2016, 9, 26, 28, 59, 59)) {
return false;
}
var border = new Date(Number(this.robberyTime) +
Number(new Date(1000 * 60 * 30)));
var newTime = this.findWithin(border,
new Date(2016, 9, 26, 28, 59, 59));
if (typeof newTime !== 'undefined') {
this.robberyTime = newTime;
return true;
}
return false;
}
};
};
/**
* Удаляет пересечение доступных интервалов с недоступными
* @param {Object} available - Доступные временные интервалы
* @param {Object} unavailable - Недоступные временные интервалы
* @returns {Object} Подходящие временные интервалы
*/
function getPossibleIntervals(available, unavailable) {
var intervalsToCheck = removeIntersection(available, unavailable);
var intervals = [];
intervalsToCheck.forEach(function (interval) {
if (interval.from <= interval.to) {
intervals.push(interval);
}
});
return intervals;
}
/**
* @param {Object} available - Доступные временные интервалы
* @param {Object} unavailable - Недоступные временные интервалы
* @returns {Object} Набор подходящих интервалов
*/
function removeIntersection(available, unavailable) {
var intervalsToCheck = [];
while (available.length > 0) {
var possible = available.pop();
var newInterval = checkIntersection(possible, unavailable);
if (typeof newInterval !== 'undefined') {
available.push(newInterval);
}
intervalsToCheck.push(possible);
}
return intervalsToCheck;
}
/**
* @param {Object} possible - Доступный временной интервал
* @param {Object} unavailable - Набор недоступных интервалов
* @returns {Object} - Новый интервал, образованный при разрыве предыдущего
*/
function checkIntersection(possible, unavailable) {
var newInterval;
unavailable.forEach(function (impossible) {
if (possible.from <= impossible.from &&
impossible.from <= possible.to &&
possible.to <= impossible.to) {
possible.to = impossible.from;
}
if (impossible.from <= possible.from &&
possible.from <= impossible.to &&
impossible.to <= possible.to) {
possible.from = impossible.to;
}
if (impossible.from <= possible.from &&
possible.from <= possible.to &&
possible.to <= impossible.to) {
possible.from = possible.to;
}
if (possible.from <= impossible.from &&
impossible.to <= possible.to) {
var tempPossibleTo = possible.to;
possible.to = impossible.from;
newInterval = {
from: impossible.to,
to: tempPossibleTo
};
}
});
return newInterval;
}
/**
* @param {Object} workHours - Часы работы
* @returns {Object} Временные интервалы в пределах задачи (ПН 00:00 - СР 23:59)
*/
function getIntervals(workHours) {
var intervals = [];
['ПН ', 'ВТ ', 'СР '].forEach(function (day) {
intervals.push({
from: day + workHours.from,
to: day + workHours.to
});
});
return intervals;
}
/**
* @param {Object} gangSchedule - Расписание Банды
* @returns {Object} Общее расписание (список из интервалов)
*/
function getCommonSchedule(gangSchedule) {
var intervals = [];
for (var gangster in gangSchedule) {
if (typeof gangster !== 'undefined') {
gangSchedule[gangster].forEach(function (interval) {
intervals.push({
from: interval.from,
to: interval.to
});
});
}
}
return intervals;
}
var DAYS = ['ВС', 'ПН', 'ВТ', 'СР'];
/**
* @param {Date} time - Время для форматирования
* @param {String} template - Шаблон
* @returns {String}
*/
function formatTime(time, template) {
var components = [
time.getHours().toString(),
time.getMinutes().toString()
];
components.forEach(function (component, idx, arr) {
if (component.length === 1) {
arr[idx] = '0' + component;
}
});
if (components[0] === '24') {
components[0] = '00';
}
return template.replace('%HH', components[0])
.replace('%MM', components[1])
.replace('%DD', DAYS[time.getDay()]);
}
/**
* @param {Object} intervals - Временные интервалы в строках
* @param {Number} timeZone - Часовой пояс банка
* @returns {Object} Временные интервалы в Date
*/
function convertIntervals(intervals, timeZone) {
intervals.forEach(function (interval) {
interval.from = convertTime(interval.from, timeZone);
interval.to = convertTime(interval.to, timeZone);
});
return intervals;
}
var DAY_TO_DATE = { 'ВС': 23, 'ПН': 24, 'ВТ': 25, 'СР': 26,
'ЧТ': 27, 'ПТ': 28, 'СББ': 29 };
/**
* @param {String} time - Строковое время
* @param {Number} timeZone - Часовой пояс банка
* @returns {Date} Время в формате Date
*/
function convertTime(time, timeZone) {
var dateParts = time.split(/[ :+]/);
var hour = parseInt(dateParts[1]) + timeZone - parseInt(dateParts[3]);
var minutes = parseInt(dateParts[2]);
return new Date(2016, 9, DAY_TO_DATE[dateParts[0]], hour, minutes);
}