-
Notifications
You must be signed in to change notification settings - Fork 77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Трофимов Павел #43
base: master
Are you sure you want to change the base?
Трофимов Павел #43
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,49 +1,198 @@ | ||
'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} | ||
*/ | ||
var days = ['ПН', 'ВТ', 'СР']; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Давай назовем как-нибудь по-другому. Задумайся, какие это дни? |
||
|
||
function getBankSchedule(bankHours, bankTimezone) { | ||
|
||
return days.map(function (day) { | ||
var from = day + ' ' + bankHours.from; | ||
var to = day + ' ' + bankHours.to; | ||
|
||
return getInterval(from, to, bankTimezone); | ||
}); | ||
} | ||
|
||
function getBankDate(date, bankTimezone) { | ||
var timeRegExp = /([А-Я]{2}) (\d{2}):(\d{2})\+(\d+)/g; | ||
var parsedTime = timeRegExp.exec(date); | ||
var day = days.indexOf(parsedTime[1]) + 1; | ||
var hour = parsedTime[2] - (parseInt(parsedTime[4]) - bankTimezone); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. у |
||
|
||
return new Date(2016, 7, day, hour, parsedTime[3]); | ||
} | ||
|
||
function parseSchedule(schedule, bankTimezone) { | ||
var parsedSchedule = []; | ||
Object.keys(schedule).forEach(function (robberName) { | ||
schedule[robberName].forEach(function (interval) { | ||
var from = interval.from; | ||
var to = interval.to; | ||
parsedSchedule.push(getInterval(from, to, bankTimezone)); | ||
}); | ||
}); | ||
|
||
return parsedSchedule; | ||
} | ||
|
||
|
||
function getInterval(from, to, timezone) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Непонятно, что за интервал ты хочешь получить |
||
|
||
return { | ||
from: getBankDate(from, timezone), | ||
to: getBankDate(to, timezone) | ||
}; | ||
} | ||
|
||
|
||
function getSotredIntervals(schedule, bankTimezone) { | ||
var sortedSchedule = parseSchedule(schedule, bankTimezone).sort(function (a, b) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. давай разобьем эту строчку: сначала ты парсишь - это одна переменная, а потом на ней вызывай метод |
||
return a.from - b.from; | ||
}); | ||
var joinedSchedule = joinSchedule(sortedSchedule); | ||
|
||
return getFreeSchedule(joinedSchedule, bankTimezone); | ||
} | ||
|
||
function checkInterval(time, interval) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В названии не отражено, на что именно ты проверяешь данный интервал. Раз ты возвращаешь булевское значение, то может быть лучше назвать как-нибудь |
||
|
||
return interval.from <= time && time <= interval.to; | ||
} | ||
|
||
function createDate(currentTime, firstTime) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. еще бы вот тут переименовать, ты же выбираешь максимум из дат, как я поняла; то есть по сути позднее из двух времен. И раз ты возвращаешь дату, то можно назвать There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ну или |
||
var greather = Math.max(currentTime, firstTime); | ||
|
||
return new Date(greather); | ||
} | ||
|
||
|
||
function joinSchedule(schedule) { | ||
var fullSchedule = []; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Полное расписание? Подумай, как по-другому это можно назвать |
||
var firstInterval = schedule[0]; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Надо переименовать, неочевидно название. Первый интервал чего? |
||
|
||
for (var i = 0; i < schedule.length; i++) { | ||
var check = checkInterval(schedule[i].from, firstInterval); | ||
|
||
if (check) { | ||
firstInterval.to = createDate(schedule[i].to, firstInterval.to); | ||
} else { | ||
fullSchedule.push(firstInterval); | ||
firstInterval = schedule[i]; | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Почему тут for, а везде выше forEach? |
||
fullSchedule.push(firstInterval); | ||
|
||
return fullSchedule; | ||
} | ||
|
||
|
||
function isCrossed(bankInterval, freeInterval) { | ||
var checkFrom = checkInterval(bankInterval.from, freeInterval); | ||
var checkTo = checkInterval(bankInterval.to, freeInterval); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здесь и в строчке выше надо переименовать переменные, они должны отражать смысл |
||
var compareIntervals = freeInterval.from > bankInterval.from && | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Надо переименовать, непонятно, что за сравнение интервалов. По переменной должно быть понятно, что в ней лежит |
||
freeInterval.to < bankInterval.to; | ||
|
||
return checkFrom || checkTo || compareIntervals; | ||
} | ||
|
||
function getBankTimezone(time) { | ||
var bankTimezone = /\+(\d+)/.exec(time)[1]; | ||
|
||
return parseInt(bankTimezone); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Укажи второй аргумент, как я писала выше |
||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ты определяешь часовой пояс банка, а потом везде его прокидываешь в качестве аргумента. Проще сохранить в переменную |
||
|
||
function getMomentForAttack(freeSchedule, bankSchedule, duration) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Может быть не |
||
var timesToAttack = []; | ||
|
||
bankSchedule.forEach(function (bankInterval) { | ||
freeSchedule.forEach(function (freeInterval) { | ||
if (isCrossed(bankInterval, freeInterval)) { | ||
var crossInterval = { | ||
from: new Date(Math.max(bankInterval.from, freeInterval.from)), | ||
to: new Date(Math.min(bankInterval.to, freeInterval.to)) | ||
}; | ||
|
||
var laterTime = new Date(crossInterval.from.getTime() + (duration * 60 * 1000)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вынеси |
||
if (checkInterval(laterTime, crossInterval)) { | ||
timesToAttack.push(crossInterval); | ||
} | ||
} | ||
}); | ||
}); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут все интервалы сравниваются с другими интервалами, но это не очень хорошо с точки зрения производительности. Зачем сравнивать время работы банка в понедельник с свободным временем грабителей во вторник или среду. Попробуй как-нибудь оптимизировать проверку по дням |
||
|
||
return timesToAttack; | ||
} | ||
|
||
function getFreeSchedule(busyTime, bankTimezone) { | ||
var freeTime = []; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. может тогда уж |
||
var interval = {}; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Непонятно, что за интервал |
||
|
||
interval.from = getBankDate('ПН 00:00+' + bankTimezone, bankTimezone); | ||
busyTime.forEach(function (currentInterval) { | ||
if (currentInterval.from === currentInterval.to) { | ||
return; | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А в каком случае может отработать это условие? Ведь если у интервала начало и конец совпадают, то это уже не интервал, а момент времени. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🍅 |
||
interval.to = currentInterval.from; | ||
freeTime.push(interval); | ||
interval = {}; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ого, какое-то 'обнуление' переменной. Можешь пояснить, что ты имел в виду? |
||
interval.from = currentInterval.to; | ||
}); | ||
interval.to = getBankDate('СР 23:59+' + bankTimezone, bankTimezone); | ||
freeTime.push(interval); | ||
|
||
return freeTime; | ||
} | ||
|
||
function formatTime(time) { | ||
|
||
return (time.toString().length === 2 ? '' : '0') + time.toString(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. На вход приходит численное значение? Может тогда лучше написать так: return (time < 10 ? '0' : '') + time; |
||
} | ||
|
||
function createLaterTime(date, shift) { | ||
|
||
return new Date(date.getTime() + (shift * 60 * 1000)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
} | ||
|
||
exports.getAppropriateMoment = function (schedule, duration, workingHours) { | ||
console.info(schedule, duration, workingHours); | ||
var bankTimezone = getBankTimezone(workingHours.from); | ||
var freeTimeIntervals = getSotredIntervals(schedule, bankTimezone); | ||
var bankSchedule = getBankSchedule(workingHours, bankTimezone); | ||
var robberyTime = getMomentForAttack(freeTimeIntervals, bankSchedule, duration); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут же массив? Значит, |
||
|
||
return { | ||
|
||
/** | ||
* Найдено ли время | ||
* @returns {Boolean} | ||
*/ | ||
exists: function () { | ||
return false; | ||
return robberyTime.length > 0; | ||
}, | ||
|
||
/** | ||
* Возвращает отформатированную строку с часами для ограбления | ||
* Например, | ||
* "Начинаем в %HH:%MM (%DD)" -> "Начинаем в 14:59 (СР)" | ||
* @param {String} template | ||
* @returns {String} | ||
*/ | ||
format: function (template) { | ||
return template; | ||
if (!this.exists()) { | ||
return ''; | ||
} | ||
|
||
var time = robberyTime[0].from; | ||
|
||
return template.replace('%HH', formatTime(time.getHours())) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Когда идет вызов нескольких функций подряд, то лучше каждую функцию начинать с новой строки. Перенеси этот |
||
.replace('%DD', days[time.getDay() - 1]) | ||
.replace('%MM', formatTime(time.getMinutes())); | ||
}, | ||
|
||
/** | ||
* Попробовать найти часы для ограбления позже [*] | ||
* @star | ||
* @returns {Boolean} | ||
*/ | ||
tryLater: function () { | ||
if (this.exists()) { | ||
var laterTime = createLaterTime(robberyTime[0].from, 30); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
var newEndTime = createLaterTime(laterTime, duration); | ||
if (checkInterval(newEndTime, robberyTime[0])) { | ||
robberyTime[0].from = laterTime; | ||
|
||
return true; | ||
} else if (robberyTime.length > 1) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. почему именно больше 1, почему не больше 0? |
||
robberyTime.shift(); | ||
|
||
return true; | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
}; | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Зачем ты удалил все JsDoc? Давай их вернем обратно. Хорошей практикой считается документировать публичные методы, так как по параметрам сложно догадаться, что они содержат