forked from urfu-2016/javascript-task-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobbery.js
178 lines (154 loc) · 5.53 KB
/
robbery.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
'use strict';
/**
* Сделано задание на звездочку
* Реализовано оба метода и tryLater
*/
exports.isStar = true;
var WEEK_DAYS = ['ВС', 'ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ'];
var WEEK_DAYS_ROBBERY = WEEK_DAYS.slice(1, 4);
var COUNT_MINUTES_LATER = 30;
function convertTime(time) {
var parametersTime = time.split(/[+:]/).map(Number);
return {
hours: parametersTime[0],
minutes: parametersTime[1],
zone: parametersTime[2]
};
}
function getDate(weekDayName, time) {
// 'Mon Oct 17 2016 00:00:01 GMT+0000'
var day = WEEK_DAYS.indexOf(weekDayName) + 16;
return new Date(Date.UTC(2016, 9, day, time.hours - time.zone, time.minutes));
}
function convertDateTime(dateTime) {
var parametersDateTime = dateTime.split(' ');
var weekDayName = parametersDateTime[0];
var time = convertTime(parametersDateTime[1]);
return getDate(weekDayName, time);
}
function compareTime(period1, period2) {
var timeDiff = period1.time - period2.time;
if (timeDiff !== 0) {
return timeDiff;
}
if (period1.type !== period2.type) {
return period1.type === 'open' ? 1 : -1;
}
return 0;
}
function periodsRobbery(schedule, workingHours) {
var periods = [];
var bankWorkingTime = {
from: convertTime(workingHours.from),
to: convertTime(workingHours.to)
};
WEEK_DAYS_ROBBERY.forEach(function (weekDayName) {
periods.push(
{ type: 'open', time: getDate(weekDayName, bankWorkingTime.from) },
{ type: 'close', time: getDate(weekDayName, bankWorkingTime.to) }
);
});
Object.keys(schedule).forEach(function (name) {
schedule[name].forEach(function (time) {
periods.push(
{ type: 'close', time: convertDateTime(time.from) },
{ type: 'open', time: convertDateTime(time.to) }
);
});
});
periods.sort(compareTime);
return periods;
}
function addZero(time) {
time = String(time);
if (time.length < 2) {
time = '0' + time;
}
return time;
}
function formatView(template, startTime, zone) {
var localDate = new Date(startTime);
localDate.setUTCHours(localDate.getUTCHours() + zone);
var hours = addZero(localDate.getUTCHours());
var minutes = addZero(localDate.getUTCMinutes());
template = template.replace(/%DD/, WEEK_DAYS[localDate.getUTCDay()]);
template = template.replace(/%HH/, hours);
template = template.replace(/%MM/, minutes);
return template;
}
/**
* @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 periods = periodsRobbery(schedule, workingHours);
var bankZone = convertTime(workingHours.from).zone;
var robberCount = Object.keys(schedule).length;
var countMatch = robberCount;
var possibleStart = null;
var allPossibleStarts = [];
var durationInMilliseconds = duration * 60 * 1000;
periods.forEach(function (period) {
countMatch = (period.type === 'open') ? countMatch + 1 : countMatch - 1;
if (countMatch === robberCount + 1) {
possibleStart = period.time;
} else if (possibleStart !== null) {
if ((period.time - possibleStart) >= durationInMilliseconds) {
allPossibleStarts.push(
{
from: possibleStart,
to: period.time
}
);
}
possibleStart = null;
}
});
var startTime = (allPossibleStarts.length !== 0) ? allPossibleStarts[0].from : null;
return {
/**
* Найдено ли время
* @returns {Boolean}
*/
exists: function () {
return startTime !== null;
},
/**
* Возвращает отформатированную строку с часами для ограбления
* Например,
* "Начинаем в %HH:%MM (%DD)" -> "Начинаем в 14:59 (СР)"
* @param {String} template
* @returns {String}
*/
format: function (template) {
return startTime !== null ? formatView(template, startTime, bankZone) : '';
},
/**
* Попробовать найти часы для ограбления позже [*]
* @star
* @returns {Boolean}
*/
tryLater: function () {
if (allPossibleStarts.length === 0) {
return false;
}
var currentTime = new Date(startTime);
currentTime.setUTCMinutes(currentTime.getUTCMinutes() + COUNT_MINUTES_LATER);
return allPossibleStarts.some(function (period) {
var nextTime = period.from;
if (currentTime > nextTime) {
nextTime = currentTime;
}
if ((period.to - nextTime) >= durationInMilliseconds) {
startTime = nextTime;
return true;
}
return false;
});
}
};
};