-
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
Козлова Валерия #57
base: master
Are you sure you want to change the base?
Козлова Валерия #57
Conversation
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
🍅 Пройдено тестов 7 из 16 |
🍅 Пройдено тестов 6 из 16 |
по временной зоне банка
🍅 Пройдено тестов 6 из 16 |
🍅 Не пройден линтинг или базовые тесты |
🍅 Не пройден линтинг или базовые тесты |
return dates[0]; | ||
} | ||
|
||
function toFreeSchedule(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.
Наверное, здесь функция должна называться getFreeTimes
? Или можешь придумать еще понятнее?
schedule.Linus.forEach(function (k) { | ||
begin = compareDate (1, i.from, j.from, k.from); | ||
end = compareDate (-1, i.to, j.to, k.to); | ||
if (end > begin) { |
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.
- Очень большая вложенность.
- Идет привязка с именам бандитов, что не есть хорошо. Вдруг они изменят состав?
- Переменные
begin
иend
инициализированы далеко от места использования, и неясно, начало и конец чего они обозначают. i
,j
,k
тоже никак себя не объясняют.
for (var i = day1; i <= Math.min(day2, 3); i++) { | ||
res.push({ | ||
from: compareDate (1, new Date (YEAR, MONTH, i, 0, 0), interval.from), | ||
to: compareDate (-1, new Date (YEAR, MONTH, i, 23, 59), interval.to) |
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 findFreeIntervals(freeTime, workingHours, res) { |
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.
Здесь больше подойдет глагол get
. Ты же его возвращаешь?)
return res; | ||
} | ||
|
||
function mainFunction(timeToRobbery, msInDuration) { |
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 mainFunction(timeToRobbery, msInDuration) { | ||
var res = []; | ||
var n = timeToRobbery.length; | ||
var c = 0; |
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.
Однобуквенных переменных вообще быть не должно, только если в крайних случаях это не цикл по индексам.
c++; | ||
} | ||
} | ||
if (c === 0) { |
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 строку тернарными операторами)
if (number < 10) { | ||
number = '0' + number; | ||
} | ||
number = String(number); |
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.
Есть метод toString
на крайний случай
console.info(schedule, duration, workingHours); | ||
var newSchedule = {}; | ||
var gmt = parseInt (workingHours.from.slice(5), 10); | ||
var msInDuration = 60 * 1000 * 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.
Ай-ай-ай, константы!
Исправлены не все замечания с прошлого раза. Советую тебе перечитать гайд по оформлению кода. |
🍅 |
🍅 Не пройден линтинг или базовые тесты |
🍅 Пройдено тестов 10 из 16 |
🍏 Пройдено тестов 16 из 16 |
var currentDay = WEEK.indexOf(dayOfWeek); | ||
var hours = parseInt(date.slice(3, 5), 10); | ||
var timeZone = parseInt(date.slice(8), 10); | ||
hours = hours - timeZone + bankTimeZone; |
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.
Это уже не просто hours
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.
можно же так: hours += bankTimeZone - timeZone
function maxDate() { | ||
var dates = [].slice.call(arguments); | ||
dates.sort(function (date1, date2) { | ||
|
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.
Почему нельзя воспользоваться функцией Math.max
?
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.
у меня не работает Math.max для дат
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.
О, давай через reduce
. Типа пройти по всем датам и найти такую, которая больше других. Очевидно, что sort
имеет сложность больше линейной - O(log(n) * n)
, а reduce
будет O(n)
return dates[0]; | ||
} | ||
|
||
function findFreeGangsterTime(schedule, bankTimeZone) { |
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.
Функция должна занимать не больше 25 строк
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.
Кажется, что можно сначала просчитать все leadToDataType(schedule[key][i].to, bankTimeZone)
для каждого 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.
И попробуй использовать reduce
|
||
function getGangFreeTime(schedule) { | ||
var freeTime = []; | ||
schedule.Danny.forEach(function (interval1) { |
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.
+1
так делать совсем нельзя - а если будет сколько угодно бандитов или имена могу быть другими?
} | ||
|
||
function formateDate(date) { | ||
var day = date.getDate(); |
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 day = WEEK[date.getDate()]
?
Почему словарь называется WEEK
? Почему метод getDate
возвращает день?
return res; | ||
} | ||
|
||
function leadDateToObject(date) { |
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 = false; | ||
|
||
var WEEK = ['', 'ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ', 'ВС']; | ||
var BEGIN_OF_WEEK = new Date (0, 0, 1, 0, 0); |
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 formateFreeTime(freeTime) { | ||
var res = []; |
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 begin = maxDate (interval1.from, interval2.from, interval3.from); | ||
var end = minDate (interval1.to, interval2.to, interval3.to); | ||
if (end > begin) { | ||
freeTime.push({ |
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.
в целом неплохо, но:
- есть косяки в названиях
- где-то слишком многословно
- совсем не используешь reduce
надо поправить, сорри за задержку - мой косяк не увидел отбивку. В следующий раз пиши в slack если буду тормозить
🍅
return freeTime; | ||
} | ||
|
||
function formateFreeTime(freeTime) { |
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.
судя по смыслу, аргумент лучше назвать freeIntervals
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.
а почему такое название функции? format
E ? Судя по коду, мы тут интервалы пересекаем с [ПН, СР] и интервалы разбиваем по дням. Это скорее некая нормализация - normalizeIntervals
for (var i = day1; i <= Math.min(day2, 3); i++) { | ||
res.push({ | ||
from: maxDate (new Date (0, 0, i, 0, 0), interval.from), | ||
to: minDate (new Date (0, 0, i, 23, 59), interval.to) |
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.
мы тут пытаемся разложить interval на отрезки по дням? и в итоге будут теже интервалы разложенные по дням - так? forEach
, который собирает некий результат - лучше писать через reduce
var res = []; | ||
freeTime.forEach(function (interval) { | ||
var day1 = interval.from.getDate(); | ||
var day2 = interval.to.getDate(); |
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.
хм, возможно, лучше назвать fromDay
и toDay
.
freeTime.forEach(function (interval) { | ||
var day1 = interval.from.getDate(); | ||
var day2 = interval.to.getDate(); | ||
for (var i = day1; i <= Math.min(day2, 3); 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.
типа не дальше среды?
function maxDate() { | ||
var dates = [].slice.call(arguments); | ||
dates.sort(function (date1, date2) { | ||
|
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.
О, давай через reduce
. Типа пройти по всем датам и найти такую, которая больше других. Очевидно, что sort
имеет сложность больше линейной - O(log(n) * n)
, а reduce
будет O(n)
to: end | ||
}); | ||
} | ||
}); |
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.
опять по смыслу reduce
= проход по массиву и получение одного результата
var bank = {}; | ||
freeTime.forEach(function (interval) { | ||
var day = interval.from.getDate(); | ||
bank.start = new Date (0, 0, day, startBankWork.hours, startBankWork.minutes); |
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.
ты часто используешь конструкцию: new Date(0, 0, x, y, z)
- кмк для нее лучше завести хелпер-функцию с говорящим именем, тогда такие вызовы будут не такими таинственными
freeTime.forEach(function (interval) { | ||
var day = interval.from.getDate(); | ||
bank.start = new Date (0, 0, day, startBankWork.hours, startBankWork.minutes); | ||
bank.end = new Date (0, 0, day, endBankWork.hours, endBankWork.minutes); |
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.
а зачем нам объект? можно было бы сделать две переменные - bankStart
и bankEnd
if (timeToRobbery[i].to - timeToRobbery[i].from >= msInDuration) { | ||
res.push(timeToRobbery[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.
опять reduce
нужен, смотри как коротко получается:
var intervals = timeToRobbery.reduce(function(res, interval) {
if (interval.to - interval.from >= msInDuration) {
res.push(interval);
}
return res;
}, []);
и в конце можно написать тернарник: return intervals.length === 0 ? nul : intervals;
@@ -24,7 +197,8 @@ exports.getAppropriateMoment = function (schedule, duration, workingHours) { | |||
* @returns {Boolean} | |||
*/ | |||
exists: function () { | |||
return false; | |||
|
|||
return (timeForRobbery !== null); |
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.