Skip to content

Трофимов Павел#43

Open
tgkd wants to merge 5 commits intourfu-2016:masterfrom
tgkd:master
Open

Трофимов Павел#43
tgkd wants to merge 5 commits intourfu-2016:masterfrom
tgkd:master

Conversation

@tgkd
Copy link
Copy Markdown

@tgkd tgkd commented Oct 26, 2016

No description provided.

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

Comment thread robbery.js
@@ -1,49 +1,198 @@
'use strict';

/**
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Зачем ты удалил все JsDoc? Давай их вернем обратно. Хорошей практикой считается документировать публичные методы, так как по параметрам сложно догадаться, что они содержат

Comment thread robbery.js Outdated
* @param {String} workingHours.to – Время закрытия, например, "18:00+5"
* @returns {Object}
*/
var days = ['ПН', 'ВТ', 'СР'];
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 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);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

у parseInt лучше указывать вторым аргументом основание системы счисления, чтобы избежать ошибок

Comment thread robbery.js Outdated
}


function getInterval(from, to, timezone) {
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 getSotredIntervals(schedule, bankTimezone) {
var sortedSchedule = parseSchedule(schedule, bankTimezone).sort(function (a, b) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread robbery.js Outdated

function joinSchedule(schedule) {
var fullSchedule = [];
var firstInterval = schedule[0];
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 joinSchedule(schedule) {
var fullSchedule = [];
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 isCrossed(bankInterval, freeInterval) {
var checkFrom = checkInterval(bankInterval.from, freeInterval);
var checkTo = checkInterval(bankInterval.to, freeInterval);
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 isCrossed(bankInterval, freeInterval) {
var checkFrom = checkInterval(bankInterval.from, freeInterval);
var checkTo = checkInterval(bankInterval.to, freeInterval);
var compareIntervals = freeInterval.from > bankInterval.from &&
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 getBankTimezone(time) {
var bankTimezone = /\+(\d+)/.exec(time)[1];

return parseInt(bankTimezone);
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 parseInt(bankTimezone);
}

function getMomentForAttack(freeSchedule, bankSchedule, 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.

Может быть не getMomentForAttack, а getMomentsForRobbery? :) + не забывай, что ты возвращаешь массив, поэтому в названии присутствует множественное число

Comment thread robbery.js Outdated
to: new Date(Math.min(bankInterval.to, freeInterval.to))
};

var laterTime = new Date(crossInterval.from.getTime() + (duration * 60 * 1000));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Вынеси 60 * 1000 в константу

Comment thread robbery.js Outdated

function getFreeSchedule(busyTime, bankTimezone) {
var freeTime = [];
var interval = {};
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 getFreeSchedule(busyTime, bankTimezone) {
var freeTime = [];
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

может тогда уж freeTimes, раз это массив

Comment thread robbery.js Outdated
}
interval.to = currentInterval.from;
freeTime.push(interval);
interval = {};
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 formatTime(time) {

return (time.toString().length === 2 ? '' : '0') + time.toString();
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 (time < 10 ? '0' : '') + time;

Comment thread robbery.js Outdated

function createLaterTime(date, shift) {

return new Date(date.getTime() + (shift * 60 * 1000));
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

60 * 1000 -> константа

Comment thread robbery.js Outdated
var bankTimezone = getBankTimezone(workingHours.from);
var freeTimeIntervals = getSotredIntervals(schedule, bankTimezone);
var bankSchedule = getBankSchedule(workingHours, bankTimezone);
var robberyTime = getMomentForAttack(freeTimeIntervals, bankSchedule, 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.

Тут же массив? Значит, robberyTimes

Comment thread robbery.js Outdated

var time = robberyTime[0].from;

return template.replace('%HH', formatTime(time.getHours()))
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Когда идет вызов нескольких функций подряд, то лучше каждую функцию начинать с новой строки. Перенеси этот replace на новую строчку. Код станет и красивее и читабельнее)

Comment thread robbery.js Outdated
*/
tryLater: function () {
if (this.exists()) {
var laterTime = createLaterTime(robberyTime[0].from, 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.

30 -> константа

Comment thread robbery.js Outdated
robberyTime[0].from = laterTime;

return true;
} else if (robberyTime.length > 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.

почему именно больше 1, почему не больше 0?

@bazhenova
Copy link
Copy Markdown

🍅

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

Comment thread robbery.js Outdated
return getFreeSchedule(joinedSchedule, bankTimezone);
}

function checkInterval(time, interval) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В названии не отражено, на что именно ты проверяешь данный интервал. Раз ты возвращаешь булевское значение, то может быть лучше назвать как-нибудь isIntersected или isIncluded или что-то в этом роде (посмотри, что больше подходит)

Comment thread robbery.js Outdated
function isCrossedIntervals(bankInterval, freeInterval) {
var checkTimeFrom = checkInterval(bankInterval.from, freeInterval);
var checkTimeTo = checkInterval(bankInterval.to, freeInterval);
var compareTimes = freeInterval.from > bankInterval.from &&
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если я правильно поняла, то compareTimes - это isRobberyTime

Comment thread robbery.js Outdated
}

function getMomentsForRobbery(freeSchedule, bankSchedule, duration) {
var timesToRob = [];
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше не сокращать слова в названиях: timesOfRobbery либо robberyTimes

@bazhenova
Copy link
Copy Markdown

И еще немного комментариев)

@bazhenova
Copy link
Copy Markdown

🍅

@bazhenova
Copy link
Copy Markdown

Ты будешь доделывать задачу?

@tgkd
Copy link
Copy Markdown
Author

tgkd commented Nov 2, 2016

@bazhenova, да, в процессе. Не знаю как правильно переименовать переменные.

@bazhenova
Copy link
Copy Markdown

@tgkd Скажи, с чем проблемы, лучше напиши в slack, помогу

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

Comment thread robbery.js Outdated
return interval.from <= time && time <= interval.to;
}

function createDate(currentTime, firstTime) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

еще бы вот тут переименовать, ты же выбираешь максимум из дат, как я поняла; то есть по сути позднее из двух времен. И раз ты возвращаешь дату, то можно назвать getLaterTime. В аргументы передавай firstTime и secondTime

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ну или getLaterDate

@bazhenova
Copy link
Copy Markdown

Еще пару переименований сделай, и я отдам тебя ментору. Вроде что-то хочется поправить, но не могу понять, что именно. Посмотрим, что скажет ментор

@bazhenova
Copy link
Copy Markdown

🍅

@honest-hrundel
Copy link
Copy Markdown

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

@honest-hrundel
Copy link
Copy Markdown

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

@bazhenova
Copy link
Copy Markdown

🚀

@gogoleff
Copy link
Copy Markdown
Contributor

gogoleff commented Nov 2, 2016

🚀

Comment thread robbery.js
var bankTimezone = /\+(\d+)/.exec(time)[1];

return parseInt(bankTimezone, 10);
}
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 getSortedIntervals(schedule, bankTimezone) {
var sortedSchedule = parseSchedule(schedule, bankTimezone);
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 getNewDate(date, bankTimezone) {
var timeRegExp = /([А-Я]{2}) (\d{2}):(\d{2})\+(\d+)/g;
var parsedTime = timeRegExp.exec(date);
var day = ROBBERY_DAYS.indexOf(parsedTime[1]) + 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.

ROBBERY_DAYS.indexOf(parsedTime[1]) + 1
В условии сказано, что проверять данные не надо, но допустим в расписании появится ЧТ. ЧТ, как день, является валидным значением, но твой код вернет 0(воскресенье), вместо 4(четверга).

Получается, что шаг в лево и твое решение перестанет работать. Надо переписать на что-то более надежное

Comment thread robbery.js
busyIntervals.push(totalBusyInterval);
totalBusyInterval = schedule[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.

Почему тут for, а везде выше forEach?

Comment thread robbery.js
var freeIntervals = [];
var currentFreeInterval = {};

currentFreeInterval.from = getNewDate('ПН 00:00+' + bankTimezone, bankTimezone);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

'ПН 00:00+' - надо унести в константы.

Comment thread robbery.js
busyTime.forEach(function (currentBusyInterval) {
if (currentBusyInterval.from === currentBusyInterval.to) {
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.

А в каком случае может отработать это условие? Ведь если у интервала начало и конец совпадают, то это уже не интервал, а момент времени.

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
}
}
});
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут все интервалы сравниваются с другими интервалами, но это не очень хорошо с точки зрения производительности. Зачем сравнивать время работы банка в понедельник с свободным временем грабителей во вторник или среду. Попробуй как-нибудь оптимизировать проверку по дням

@ulitcos
Copy link
Copy Markdown

ulitcos commented Nov 7, 2016

🍅

@ulitcos
Copy link
Copy Markdown

ulitcos commented Dec 12, 2016

Последняя активность 7-го ноября

@ulitcos ulitcos removed their assignment Dec 12, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants