Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
211 changes: 180 additions & 31 deletions robbery.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,198 @@
'use strict';

/**
* Сделано задание на звездочку
* Реализовано оба метода и tryLater
*/
exports.isStar = 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.

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


/**
* @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 = ['ПН', 'ВТ', 'СР'];
Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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);
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 лучше указывать вторым аргументом основание системы счисления, чтобы избежать ошибок


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) {
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 {
from: getBankDate(from, timezone),
to: getBankDate(to, timezone)
};
}


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 - тебе не придется создавать новую переменную, так как данный метод изменяет исходный массив

return a.from - b.from;
});
var joinedSchedule = joinSchedule(sortedSchedule);

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 или что-то в этом роде (посмотри, что больше подходит)


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

var greather = Math.max(currentTime, firstTime);

return new Date(greather);
}


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.

Полное расписание? Подумай, как по-другому это можно назвать

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.

Надо переименовать, неочевидно название. Первый интервал чего?


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];
}
}
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?

fullSchedule.push(firstInterval);

return fullSchedule;
}


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.

Здесь и в строчке выше надо переименовать переменные, они должны отражать смысл

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.

Надо переименовать, непонятно, что за сравнение интервалов. По переменной должно быть понятно, что в ней лежит

freeInterval.to < bankInterval.to;

return checkFrom || checkTo || compareIntervals;
}

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.

Укажи второй аргумент, как я писала выше

}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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


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? :) + не забывай, что ты возвращаешь массив, поэтому в названии присутствует множественное число

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));
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 в константу

if (checkInterval(laterTime, crossInterval)) {
timesToAttack.push(crossInterval);
}
}
});
});
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 timesToAttack;
}

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, раз это массив

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.

Непонятно, что за интервал


interval.from = getBankDate('ПН 00:00+' + bankTimezone, bankTimezone);
busyTime.forEach(function (currentInterval) {
if (currentInterval.from === currentInterval.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.

🍅

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.

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

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();
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;

}

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 -> константа

}

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


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()))
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 на новую строчку. Код станет и красивее и читабельнее)

.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);
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 -> константа

var newEndTime = createLaterTime(laterTime, duration);
if (checkInterval(newEndTime, robberyTime[0])) {
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?

robberyTime.shift();

return true;
}
}

return false;
}
};
Expand Down