Skip to content

Левшин Михаил#18

Open
LevshinMisha wants to merge 8 commits intourfu-2016:masterfrom
LevshinMisha:master
Open

Левшин Михаил#18
LevshinMisha wants to merge 8 commits intourfu-2016:masterfrom
LevshinMisha:master

Conversation

@LevshinMisha
Copy link
Copy Markdown

No description provided.

@honest-hrundel
Copy link
Copy Markdown

🍏 Пройдено тестов 19 из 19

@honest-hrundel
Copy link
Copy Markdown

@chipolinka обрати внимание решено доп. задание

Comment thread robbery.js Outdated
* @param {String} workingHours.to – Время закрытия, например, "18:00+5"
* @returns {Object}
*/
var daysDict = { 'ПН': 0, 'ВТ': 1, 'СР': 2 };
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это константа? посмотри, как в гайде рекомендуют называть константы.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да Это по сути константа. Исправлю

Comment thread robbery.js Outdated
* @returns {Object}
*/
var daysDict = { 'ПН': 0, 'ВТ': 1, 'СР': 2 };
var daysArray = ['ПН', 'ВТ', 'СР'];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем тебе этот массив? можно просто взять ключи словаря)

Copy link
Copy Markdown
Author

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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по-моему, это не повод у всех словарей выделять ключи в массив) в конце концов, можешь уж список-то заново не создавать

Comment thread robbery.js Outdated
};

this.getNextDay = function () {
return new TimeInterval(this.start + 24 * 60, this.end + 24 * 60);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

числа нужно вынести в константы

Comment thread robbery.js Outdated
return new TimeInterval(this.start + 24 * 60, this.end + 24 * 60);
};

this.timeInInterval = function (time) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в названии функции надо указывать, что она делает (то бишь глагол)

Comment thread robbery.js Outdated
};
}

function timeInIntervals(timeIntervalsArray, time) {
Copy link
Copy Markdown

@chipolinka chipolinka Oct 24, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

аналогично с timeInInterval

Comment thread robbery.js
for (var i = 0; i < timeIntervalsArray.length; i++) {
if (timeIntervalsArray[i].timeInInterval(time)) {

return true;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а зачем тут отступ перед return?)

Comment thread robbery.js Outdated
var day = 0;
if (daysDict[str.slice(0, 2)] !== undefined) {
day = daysDict[str.split(' ')[0]];
str = str.split(' ')[1];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

str.split(' ') наверное стоит вынести в переменную, раз часто используется

Comment thread robbery.js Outdated
var h = parseInt(str.split(':')[0]);
var m = parseInt(str.split(':')[1]);

return day * 24 * 60 + (h - timezone) * 60 + m;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

константы

Comment thread robbery.js Outdated
var timezone = parseInt(str.split('+')[1]);
str = str.split('+')[0];
var h = parseInt(str.split(':')[0]);
var m = parseInt(str.split(':')[1]);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

по-моему, это не самое подходящее название переменной. мало ли чего там m может быть?) да и h тоже

Comment thread robbery.js Outdated
});
});
newSchedule.Bank.push(new TimeInterval(strToIntDate(workingHours.from) +
bankTimezone * 60, strToIntDate(workingHours.to) + bankTimezone * 60));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

кажется, тут есть дублирование... и константы, конечно.

Comment thread robbery.js Outdated
}
}

for (; i < 3 * 24 * 60; i++) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ой, как много констант

Comment thread robbery.js Outdated
var i = 0;
function gangsterNotBusy(gangster) {
if (timeInIntervals(newSchedule[gangster], i)) {
goodTimeToHack = false;
Copy link
Copy Markdown

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) ?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В случае если время неподходит первому, но подходит второму и третьему, то значение переменной будет true. Что не совсем то что нужно.

Comment thread robbery.js Outdated

var goodTimeToHack = true;
var i = 0;
function gangsterNotBusy(gangster) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

опять имя функции не по канону

Comment thread robbery.js Outdated
function simplifyTimesIntervals() {
var newTimeIntervals = [];
goodTimesIntervals.forEach(function (timeInterval) {
if (!(timeInterval.getLength() < duration)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

просто интересно: а почему не >=? а именно отрицание от <?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Потому что я могу)

Comment thread robbery.js Outdated
tryLater: function () {
if (this.exists()) {
var startInterval = goodTimesIntervals[0];
if (goodTimesIntervals.length > 1 || startInterval.getLength() >= duration + 30) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

кажется, что это можно переписать в один if, ну или как-то более сокращенно

@chipolinka
Copy link
Copy Markdown

везде есть константы, которые надо вынести/переименовать.

@chipolinka
Copy link
Copy Markdown

🍅

@honest-hrundel
Copy link
Copy Markdown

🍅 Не пройден линтинг или базовые тесты

@honest-hrundel
Copy link
Copy Markdown

🍏 Пройдено тестов 19 из 19

@honest-hrundel
Copy link
Copy Markdown

@chipolinka обрати внимание решено доп. задание

Comment thread robbery.js Outdated
};
}

function timeIsInIntervals(timeIntervalsArray, time) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше isTimeInIntervals

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и аналогично во всех остальных местах)

Comment thread robbery.js Outdated
});
newSchedule.Bank.push(new TimeInterval(
strToIntDate(workingHours.from) + bankTimezone * MINUTES_IN_HOUR,
strToIntDate(workingHours.to) + bankTimezone * MINUTES_IN_HOUR));
Copy link
Copy Markdown

@chipolinka chipolinka Oct 24, 2016

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

Comment thread robbery.js Outdated

function createGoodTimesIntArray() {

var goodTimeToHack = true;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

иногда отступы всплывают в самых неожиданных местах. не рекомендую их ставить после фигурных скобочек (не только здесь, но и во всём коде). тут же нечего отделять логически?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а ещё название этой переменной предполагает, что в ней хранится время.

Comment thread robbery.js Outdated

var goodTimeToHack = true;
var i = 0;
function gangsterIsNotBusy(gangster) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

название функции следует начинать с глагола

@honest-hrundel
Copy link
Copy Markdown

@chipolinka обрати внимание решено доп. задание

@honest-hrundel
Copy link
Copy Markdown

🍏 Пройдено тестов 19 из 19

@honest-hrundel
Copy link
Copy Markdown

@chipolinka обрати внимание решено доп. задание

Comment thread robbery.js Outdated
var i = -1;
function isGangsterNotBusy(gangster) {
if (isTimeInIntervals(schedule[gangster], i)) {
isGoodTimeToHack = false;
Copy link
Copy Markdown

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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделать, то можно. Только это не совсем правильно(я уже писал почему). Даже базовые тесты перестают проходить.

Comment thread robbery.js Outdated
}
}

while (i < DAYS_TO_HACK * MINUTES_IN_DAY) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном while у тебя i не изменяется, кроме как увеличивается при каждой итерации? Почему бы тогда не сделать это циклом?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

функция isGangsterNotBusy использует внешние переменные, одной из которой является переменная i. А так как функции объявлять внутри цикла нельзя(lint), то следовательно нужно объявить эту переменную и функцию ее использующую заранее. Я вижу выход из этой ситуации созданием функции, которая возвращает другую функцию. Попробую это сделать.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

исправил даже изящнее чем сам предполагал)

Comment thread robbery.js Outdated
if (!isTimeInIntervals(schedule.Bank, i)) {
continue;
}
gangsterNames.forEach(isGangsterNotBusy);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А зачем ты это вынес в отдельную функцию? У тебя она вынесена далеко от этого места, да и содержит в себе 1 строчку...

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В lint'е стоит ограничение, что нельзя создавать функции внутри цикла

Comment thread robbery.js Outdated

function createScheduleWithTimeIntervals(bankWorkingHours, schedule, gangsterNames) {
var newSchedule = {};
var bankShift = parseInt(bankWorkingHours.from.split('+')[1], 10) * MINUTES_IN_HOUR;
Copy link
Copy Markdown

@chipolinka chipolinka Oct 28, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень сложная строка. И давай у тебя весь парсинг будет вынесен в одно место?

Comment thread robbery.js Outdated
return goodTimesIntervals;
}

function createScheduleWithTimeIntervals(bankWorkingHours, schedule, gangsterNames) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эту функцию можно разбить на наполнение нового расписания гангстерами и банком. И объединить результат как раз в этой функции.

Comment thread robbery.js Outdated
var gangsterNames = getGangsterNames(schedule);
var newSchedule = createScheduleWithTimeIntervals(workingHours, schedule, gangsterNames);
var goodTimesIntervals = getGoodTimeIntervals(newSchedule, gangsterNames);
goodTimesIntervals = simplifyTimesIntervals(goodTimesIntervals, duration);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше создай новую переменную с соответствующим названием. А то не ясно, чем результат этой функции отличается от предыдущей. А так -- мне нравится организация кода 👍

Comment thread robbery.js
return template;
if (!this.exists()) {

return '';
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется, тут лишний перенос строки

Comment thread robbery.js
function getGangsterNames(schedule) {
var gangsterNames = [];
for (var gangsterName in schedule) {
if (schedule.hasOwnProperty(gangsterName)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Попробуй написать это как-то по-другому. Попроще :)

Copy link
Copy Markdown
Author

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread robbery.js
exports.isStar = true;

/**
* @param {Object} schedule – Расписание Банды
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему удалил доки?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

мешает

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Но они же несут полезную информацию!

Comment thread robbery.js Outdated
return false;
}

function strDateToInt(strDate) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если честно, на первый взгляд тут адище происходит. Слайсы не подойдут?

@chipolinka
Copy link
Copy Markdown

🍅

@honest-hrundel
Copy link
Copy Markdown

🍏 Пройдено тестов 19 из 19

@honest-hrundel
Copy link
Copy Markdown

@chipolinka обрати внимание решено доп. задание

Comment thread robbery.js Outdated
if (DAYS_INDEXES[strDateCopy.slice(0, 2)] === undefined) {
strDateCopy = 'ПН ' + strDateCopy;
}
var o = {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что это за название такое?)

Comment thread robbery.js Outdated

function addOrChangeLastTimeInterval(arrayIntervals, timeToStartNewInterval) {
if (arrayIntervals.length === 0 ||
arrayIntervals[arrayIntervals.length - 1].end !== timeToStartNewInterval - 1) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В этой функции слишком часто используется arrayIntervals.length, лучше вынеси в отдельную переменную. Да и название покороче будет)

Comment thread robbery.js
var gangstersIsNotBusy = true;
gangsterNames.forEach(function (gangster) {
if (isTimeInIntervals(schedule[gangster], time)) {
gangstersIsNotBusy = false;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно написать здесь return false;, а в конце функции -- return true;. Тогда без этой переменной обойдемся и меньше бегать по циклу будем)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

К сожалению из forEach нельзя ничего возвращать(

@chipolinka
Copy link
Copy Markdown

В целом стало намного лучше, молодец. Исправь мелкие замечания, и я передаю тебя ментору.

@chipolinka
Copy link
Copy Markdown

🚀

@honest-hrundel honest-hrundel assigned mokhov and unassigned chipolinka Oct 28, 2016
@honest-hrundel
Copy link
Copy Markdown

🍏 Пройдено тестов 19 из 19

@honest-hrundel
Copy link
Copy Markdown

@mokhov обрати внимание решено доп. задание

Copy link
Copy Markdown

@mokhov mokhov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном решении очень много избыточного кода. Из-за этого его очень сложно читать. Хочу в ответном комментарии увидеть ответ на вопрос: как работает твой алгоритм?

Comment thread robbery.js
exports.isStar = true;

var DAYS_INDEXES = { 'ПН': 0, 'ВТ': 1, 'СР': 2, 'ЧТ': 3, 'ПТ': 4, 'СБ': 5, 'ВС': 6 };
var DAYS_NAMES = ['ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ', 'ВС'];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это ключи предыдущего объекта

Comment thread robbery.js
};
}

function isTimeInIntervals(timeIntervalsArray, time) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название читаю, а понять что она делает не могу

Comment thread robbery.js
}

function strDateToDateObj(strDate) {
var strDateCopy = strDate.slice();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем это нужно?

Comment thread robbery.js
function getGangsterNames(schedule) {
var gangsterNames = [];
for (var gangsterName in schedule) {
if (schedule.hasOwnProperty(gangsterName)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread robbery.js
this.start = start;
this.end = end;

this.getLength = function () {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

start и end известны на этапе создания объекта, почему length нужно вычислять, а нельзя сделать полем?

Comment thread robbery.js
}

function createTimeIntervalWithShift(time, shift) {
return new TimeInterval(strDateToDateObj(time.from).intValue + shift,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это нечитаемый однострочник, нужно вынести аргументы TimeIntreval в читаемые переменные

Comment thread robbery.js
strDateToDateObj(time.to).intValue + shift);
}

function simplifyTimesIntervals(timeIntervals, duration) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Название функции переводится как «Упростить временные интервалы». Я честно не понимаю что тут подразумевается

Comment thread robbery.js

function simplifyTimesIntervals(timeIntervals, duration) {
var newTimeIntervals = [];
timeIntervals.forEach(function (timeInterval) {
Copy link
Copy Markdown

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

Comment thread robbery.js
return newTimeIntervals;
}

function addOrChangeLastTimeInterval(arrayIntervals, timeToStartNewInterval) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Из названия функции абсолютно не понятно что она делает. И по коду я тоже ничего не понял

@mokhov
Copy link
Copy Markdown

mokhov commented Oct 30, 2016

🍅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants