-
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
Левшин Михаил #18
base: master
Are you sure you want to change the base?
Левшин Михаил #18
Conversation
🍏 Пройдено тестов 19 из 19 |
@chipolinka обрати внимание решено доп. задание |
* @param {String} workingHours.to – Время закрытия, например, "18:00+5" | ||
* @returns {Object} | ||
*/ | ||
var daysDict = { 'ПН': 0, 'ВТ': 1, 'СР': 2 }; |
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.
это константа? посмотри, как в гайде рекомендуют называть константы.
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.
Да Это по сути константа. Исправлю
* @returns {Object} | ||
*/ | ||
var daysDict = { 'ПН': 0, 'ВТ': 1, 'СР': 2 }; | ||
var daysArray = ['ПН', 'ВТ', 'СР']; |
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.
зачем тебе этот массив? можно просто взять ключи словаря)
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.
Для читаемости кода. daysDict.keys()[i] хуже чем daysArray[i]
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.
по-моему, это не повод у всех словарей выделять ключи в массив) в конце концов, можешь уж список-то заново не создавать
}; | ||
|
||
this.getNextDay = function () { | ||
return new TimeInterval(this.start + 24 * 60, this.end + 24 * 60); |
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.
числа нужно вынести в константы
return new TimeInterval(this.start + 24 * 60, this.end + 24 * 60); | ||
}; | ||
|
||
this.timeInInterval = function (time) { |
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.
в названии функции надо указывать, что она делает (то бишь глагол)
}; | ||
} | ||
|
||
function timeInIntervals(timeIntervalsArray, time) { |
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.
аналогично с timeInInterval
for (var i = 0; i < timeIntervalsArray.length; i++) { | ||
if (timeIntervalsArray[i].timeInInterval(time)) { | ||
|
||
return true; |
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.
а зачем тут отступ перед return?)
var day = 0; | ||
if (daysDict[str.slice(0, 2)] !== undefined) { | ||
day = daysDict[str.split(' ')[0]]; | ||
str = str.split(' ')[1]; |
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.
str.split(' ')
наверное стоит вынести в переменную, раз часто используется
var h = parseInt(str.split(':')[0]); | ||
var m = parseInt(str.split(':')[1]); | ||
|
||
return day * 24 * 60 + (h - timezone) * 60 + m; |
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.
константы
var timezone = parseInt(str.split('+')[1]); | ||
str = str.split('+')[0]; | ||
var h = parseInt(str.split(':')[0]); | ||
var m = parseInt(str.split(':')[1]); |
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.
по-моему, это не самое подходящее название переменной. мало ли чего там m
может быть?) да и h
тоже
}); | ||
}); | ||
newSchedule.Bank.push(new TimeInterval(strToIntDate(workingHours.from) + | ||
bankTimezone * 60, strToIntDate(workingHours.to) + bankTimezone * 60)); |
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.
кажется, тут есть дублирование... и константы, конечно.
} | ||
} | ||
|
||
for (; i < 3 * 24 * 60; i++) { |
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.
ой, как много констант
var i = 0; | ||
function gangsterNotBusy(gangster) { | ||
if (timeInIntervals(newSchedule[gangster], i)) { | ||
goodTimeToHack = 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.
goodTimeToHack = !timeInIntervals(newSchedule[gangster], i)
?
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.
В случае если время неподходит первому, но подходит второму и третьему, то значение переменной будет true. Что не совсем то что нужно.
|
||
var goodTimeToHack = true; | ||
var i = 0; | ||
function gangsterNotBusy(gangster) { |
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.
опять имя функции не по канону
function simplifyTimesIntervals() { | ||
var newTimeIntervals = []; | ||
goodTimesIntervals.forEach(function (timeInterval) { | ||
if (!(timeInterval.getLength() < duration)) { |
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.
просто интересно: а почему не >=
? а именно отрицание от <
?
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.
Потому что я могу)
tryLater: function () { | ||
if (this.exists()) { | ||
var startInterval = goodTimesIntervals[0]; | ||
if (goodTimesIntervals.length > 1 || startInterval.getLength() >= duration + 30) { |
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.
кажется, что это можно переписать в один if
, ну или как-то более сокращенно
везде есть константы, которые надо вынести/переименовать. |
🍅 |
🍅 Не пройден линтинг или базовые тесты |
🍏 Пройдено тестов 19 из 19 |
@chipolinka обрати внимание решено доп. задание |
}; | ||
} | ||
|
||
function timeIsInIntervals(timeIntervalsArray, time) { |
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.
лучше isTimeInIntervals
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.
и аналогично во всех остальных местах)
}); | ||
newSchedule.Bank.push(new TimeInterval( | ||
strToIntDate(workingHours.from) + bankTimezone * MINUTES_IN_HOUR, | ||
strToIntDate(workingHours.to) + bankTimezone * MINUTES_IN_HOUR)); |
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.
меня смущает, что у тебя 4 раза встречается строка
strToIntDate(something) + bankTimezone * MINUTES_IN_HOUR
это никак не сделать поизящнее?
имею в виду DRY
|
||
function createGoodTimesIntArray() { | ||
|
||
var goodTimeToHack = true; |
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.
иногда отступы всплывают в самых неожиданных местах. не рекомендую их ставить после фигурных скобочек (не только здесь, но и во всём коде). тут же нечего отделять логически?
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.
а ещё название этой переменной предполагает, что в ней хранится время.
|
||
var goodTimeToHack = true; | ||
var i = 0; | ||
function gangsterIsNotBusy(gangster) { |
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.
название функции следует начинать с глагола
@chipolinka обрати внимание решено доп. задание |
🍏 Пройдено тестов 19 из 19 |
@chipolinka обрати внимание решено доп. задание |
var i = -1; | ||
function isGangsterNotBusy(gangster) { | ||
if (isTimeInIntervals(schedule[gangster], i)) { | ||
isGoodTimeToHack = 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.
можно сделать isGoodTimeToHack = !isTimeInIntervals(schedule[gangster], i)
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.
Сделать, то можно. Только это не совсем правильно(я уже писал почему). Даже базовые тесты перестают проходить.
} | ||
} | ||
|
||
while (i < DAYS_TO_HACK * MINUTES_IN_DAY) { |
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.
В данном while
у тебя i
не изменяется, кроме как увеличивается при каждой итерации? Почему бы тогда не сделать это циклом?
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.
функция isGangsterNotBusy использует внешние переменные, одной из которой является переменная i. А так как функции объявлять внутри цикла нельзя(lint), то следовательно нужно объявить эту переменную и функцию ее использующую заранее. Я вижу выход из этой ситуации созданием функции, которая возвращает другую функцию. Попробую это сделать.
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.
исправил даже изящнее чем сам предполагал)
if (!isTimeInIntervals(schedule.Bank, i)) { | ||
continue; | ||
} | ||
gangsterNames.forEach(isGangsterNotBusy); |
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.
А зачем ты это вынес в отдельную функцию? У тебя она вынесена далеко от этого места, да и содержит в себе 1 строчку...
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.
В lint'е стоит ограничение, что нельзя создавать функции внутри цикла
|
||
function createScheduleWithTimeIntervals(bankWorkingHours, schedule, gangsterNames) { | ||
var newSchedule = {}; | ||
var bankShift = parseInt(bankWorkingHours.from.split('+')[1], 10) * MINUTES_IN_HOUR; |
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.
Очень сложная строка. И давай у тебя весь парсинг будет вынесен в одно место?
return goodTimesIntervals; | ||
} | ||
|
||
function createScheduleWithTimeIntervals(bankWorkingHours, schedule, gangsterNames) { |
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.
Эту функцию можно разбить на наполнение нового расписания гангстерами и банком. И объединить результат как раз в этой функции.
var gangsterNames = getGangsterNames(schedule); | ||
var newSchedule = createScheduleWithTimeIntervals(workingHours, schedule, gangsterNames); | ||
var goodTimesIntervals = getGoodTimeIntervals(newSchedule, gangsterNames); | ||
goodTimesIntervals = simplifyTimesIntervals(goodTimesIntervals, duration); |
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.
Лучше создай новую переменную с соответствующим названием. А то не ясно, чем результат этой функции отличается от предыдущей. А так -- мне нравится организация кода 👍
return template; | ||
if (!this.exists()) { | ||
|
||
return ''; |
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.
Кажется, тут лишний перенос строки
function getGangsterNames(schedule) { | ||
var gangsterNames = []; | ||
for (var gangsterName in schedule) { | ||
if (schedule.hasOwnProperty(gangsterName)) { |
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.
Попробуй написать это как-то по-другому. Попроще :)
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.
Ну если честно я не знаю как. https://learn.javascript.ru/object-for-in смотрел тут. hasOwnProperty для lint'a
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.
exports.isStar = true; | ||
|
||
/** | ||
* @param {Object} schedule – Расписание Банды |
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.
Почему удалил доки?
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.
мешает
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.
Но они же несут полезную информацию!
return false; | ||
} | ||
|
||
function strDateToInt(strDate) { |
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.
Если честно, на первый взгляд тут адище происходит. Слайсы не подойдут?
🍅 |
🍏 Пройдено тестов 19 из 19 |
@chipolinka обрати внимание решено доп. задание |
if (DAYS_INDEXES[strDateCopy.slice(0, 2)] === undefined) { | ||
strDateCopy = 'ПН ' + strDateCopy; | ||
} | ||
var o = { |
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.
Что это за название такое?)
|
||
function addOrChangeLastTimeInterval(arrayIntervals, timeToStartNewInterval) { | ||
if (arrayIntervals.length === 0 || | ||
arrayIntervals[arrayIntervals.length - 1].end !== timeToStartNewInterval - 1) { |
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.
В этой функции слишком часто используется arrayIntervals.length
, лучше вынеси в отдельную переменную. Да и название покороче будет)
var gangstersIsNotBusy = true; | ||
gangsterNames.forEach(function (gangster) { | ||
if (isTimeInIntervals(schedule[gangster], time)) { | ||
gangstersIsNotBusy = 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.
Можно написать здесь return false;
, а в конце функции -- return true;
. Тогда без этой переменной обойдемся и меньше бегать по циклу будем)
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.
К сожалению из forEach нельзя ничего возвращать(
В целом стало намного лучше, молодец. Исправь мелкие замечания, и я передаю тебя ментору. |
🚀 |
🍏 Пройдено тестов 19 из 19 |
@mokhov обрати внимание решено доп. задание |
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.
В данном решении очень много избыточного кода. Из-за этого его очень сложно читать. Хочу в ответном комментарии увидеть ответ на вопрос: как работает твой алгоритм?
@@ -6,6 +6,156 @@ | |||
*/ | |||
exports.isStar = true; | |||
|
|||
var DAYS_INDEXES = { 'ПН': 0, 'ВТ': 1, 'СР': 2, 'ЧТ': 3, 'ПТ': 4, 'СБ': 5, 'ВС': 6 }; | |||
var DAYS_NAMES = ['ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ', 'ВС']; |
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.
Это ключи предыдущего объекта
}; | ||
} | ||
|
||
function isTimeInIntervals(timeIntervalsArray, time) { |
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.
Название читаю, а понять что она делает не могу
} | ||
|
||
function strDateToDateObj(strDate) { | ||
var strDateCopy = strDate.slice(); |
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.
Зачем это нужно?
function getGangsterNames(schedule) { | ||
var gangsterNames = []; | ||
for (var gangsterName in schedule) { | ||
if (schedule.hasOwnProperty(gangsterName)) { |
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.
this.start = start; | ||
this.end = end; | ||
|
||
this.getLength = function () { |
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.
start
и end
известны на этапе создания объекта, почему length
нужно вычислять, а нельзя сделать полем?
} | ||
|
||
function createTimeIntervalWithShift(time, shift) { | ||
return new TimeInterval(strDateToDateObj(time.from).intValue + shift, |
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.
Это нечитаемый однострочник, нужно вынести аргументы TimeIntreval в читаемые переменные
strDateToDateObj(time.to).intValue + shift); | ||
} | ||
|
||
function simplifyTimesIntervals(timeIntervals, duration) { |
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.
Название функции переводится как «Упростить временные интервалы». Я честно не понимаю что тут подразумевается
|
||
function simplifyTimesIntervals(timeIntervals, duration) { | ||
var newTimeIntervals = []; | ||
timeIntervals.forEach(function (timeInterval) { |
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.
Для фильтрации массивов придумали специальную функцию https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
return newTimeIntervals; | ||
} | ||
|
||
function addOrChangeLastTimeInterval(arrayIntervals, timeToStartNewInterval) { |
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.
Из названия функции абсолютно не понятно что она делает. И по коду я тоже ничего не понял
🍅 |
No description provided.