Skip to content
Open
Show file tree
Hide file tree
Changes from 7 commits
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
55 changes: 55 additions & 0 deletions collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
var Collection = function (items) {
'use strict';
var item;
this.items = [];
for (item in items) {
if (items.hasOwnProperty(item)) {
if (items[item].validate()) {
this.items.push(items[item]);
}
}
}
};

/**
* @return {Collection}
*/
Collection.prototype =
{
add : function (model) {
'use strict';
if (model.validate()) {
this.items.push(model);
}
},
/**
* Фильтрация коллекции по правилам, определенным в функции selector
*
* @param {Function} selector
*
* @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
*
* @return {Collection}
*/
filter : function (selector) {
'use strict';
var tmp = this.items.filter(selector);
return new this.constructor(tmp);
},
/**
* Сортировка коллекции по правилам, определенным в функции selector
*
* @param {Function} selector
* @param {Boolean} asc
*
* @return {Collection}
*/
sortBy : function (selector, asc) {
'use strict';
this.items.sort(selector);
if (asc) {
this.items.reverse();
}
return this;
}
};
27 changes: 27 additions & 0 deletions event-collection.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<title>EVents test</title>

</head>

<body>

<div class="container">

<input type="button" onclick="console.dir(events.findFutureEvents().findThisWeekEvents());" value = "будущие события недели"/>
<input type="button" onclick="console.dir(events.findFutureEvents().findPartyEvents().sortByStartDate());" value = "будущие пьянки, отсортированные по дате"/>
<input type="button" onclick="console.dir(events.findFutureEvents().findThisWeekEvents().findNightAlarms().sortByNextHappenDate());" value = "события, которые меня разбудят на этой неделе"/>

</div>

<script src="model.js"></script>
<script src="collection.js"></script>
<script src="event-model.js"></script>
<script src="event-collection.js"></script>
<script src="utils.js"></script>

</body>
</html>
78 changes: 78 additions & 0 deletions event-collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
var Events = function (items) {
'use strict';
Collection.apply(this, arguments);
};
inherits(Events, Collection);

Events.prototype.constructor = Events;
/**
* Возвращает новую коллекцию, содержащую только прошедшие события
* @return {Events}
*/
Events.prototype.findPastEvents = function () {
'use strict';
return this.filter(function (event) {
return event.endDate < new Date();
});
};
/**
* Возвращает новую коллекцию, содержащую только будущие события
* @return {Events}
*/
Events.prototype.findFutureEvents = function () {
'use strict';
return this.filter(function (event) {
return event.startDate > new Date();
});
};
/**
* Возвращает новую коллекцию, содержащую только события этой недели
* @return {Events}
*/
Events.prototype.findThisWeekEvents = function () {
'use strict';
return this.filter(function (event) {
return event.startDate > Utils.getWeekStartDate() && event.startDate < Utils.getWeekEndDate();
});
};
/**
* Возвращает новую коллекцию, содержащую только события 'Drunken feast'
* @return {Events}
*/
Events.prototype.findPartyEvents = function () {
'use strict';
return this.filter(function (event) {
return event.title === 'Drunken feast';
});
};
/**
* Возвращает новую коллекцию, содержащую только те события, напоминание которых сработает ночью
* @return {Events}
*/
Events.prototype.findNightAlarms = function () {
'use strict';
return this.filter(function (event) {
var alarm = event.getNextAlarmTime();
return alarm.getHours() > 0 && alarm.getHours() < 8;
});
};
/**
* Сортирует коллекцию по дате начала события
* @return {Events}
*/
Events.prototype.sortByStartDate = function (asc) {
'use strict';
return this.sortBy(function (a, b) {
return b.startDate - a.startDate;
}, asc);
};
/**
* Сортирует коллекцию по следующей дате периодического события
* @return {Events}
*/
Events.prototype.sortByNextHappenDate = function (asc) {
'use strict';
return this.sortBy(function (a, b) {
return b.getNextHappenDate() - a.getNextHappenDate();
}, asc);
};
169 changes: 169 additions & 0 deletions event-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/*jslint devel: true */
function checkStartDate(date) {
'use strict';
if (date === null) {
date = new Date();
} else if (!(date instanceof Date && isFinite(date))) {
console.log("Start date is invalid, check syntax");
date = null;
}
return date;
}

function checkEndDate(endDate, startDate) {
'use strict';
var date;
if (endDate === null) {
date = startDate;
date.setHours(startDate.getHours() + 1);
} else if (endDate instanceof Date && isFinite(endDate)) {
if (endDate < startDate) {
console.log("End date should be after start date");
date = null;
} else {
date = endDate;
}
} else {
console.log("End date is invalid, check syntax");
date = null;
}
return date;
}

function checkAddTime(addTime) {
'use strict';
var re, splitted;
re = "([+-]) (\\d?\\d.\\d?\\d.\\d?\\d) (\\d?\\d:\\d?\\d)";
splitted = addTime.match(re);
if (splitted === null || splitted.length !== 4) {
splitted = null;
}
return splitted;
}

function checkRepeat(repeat) {
'use strict';
if (repeat === null) {
repeat = Const.REPEAT.NEVER;
} else if (!(repeat.title && repeat.value)) {
console.log("Unknown type of 'repeat' variable");
repeat = null;
} else if (!checkAddTime(repeat.value)) {
console.log("Add time in 'repeat' variable must have format '+ dd.MM.YY hh:mm'");
repeat = null;
}
return repeat;
}

function checkAlert(alert) {
'use strict';
if (alert === null) {
alert = Const.ALERT.NONE;
} else if (!(alert.title && alert.value)) {
console.log("Unknown type of 'alert' variable");
alert = null;
} else if (!checkAddTime(alert.value)) {
console.log("Add time in 'alert' variable must have format '+ dd.MM.YY hh:mm'");
alert = null;
}
return alert;
}
/**
* Создает объект Event
*
* @param {String} [title="New Event"] Имя события
* @param {String} [location] Место события
* @param {Number|Date} [starts="new Date()"] Начало события
* @param {Number|Date} [ends="starts + 1"] Конец события
* @param {Object} [repeat="Const.REPEAT.NEVER"] Периодичность события
* @param {Object} [alert="Const.ALERT.NONE"] Предупреждение
* @param {String} [notes] Заметки
*
* @example
* new Event({title: "Лекция JavaScript",
* location: "УРГУ",
* startDate: new Date('2011-10-10T14:48:00'),
* endDate: new Date('2011-10-10T15:48:00'),
* repeat: REPEAT.WEEK,
* alert: ALERT.B30MIN,
* notes: "Вспомнить, что проходили на прошлом занятии"})
*
* @return {Event}
*/
var Event = function (data) {
'use strict';
Model.apply(this, arguments);
};
inherits(Event, Model);

Event.prototype.constructor = Event;

/**
* Функция, валидирующая объект Event
*
* @return {Event}
*/
Event.prototype.validate = function () {
'use strict';
this.startDate = checkStartDate(this.startDate);
if (this.startDate === null) {
return;
}
this.endDate = checkEndDate(this.endDate, this.startDate);
if (this.endDate === null) {
return;
}
this.repeat = checkRepeat(this.repeat);
if (this.repeat === null) {
return;
}
this.alert = checkAlert(this.alert);
if (this.alert === null) {
return;
}
return this;
};
/**
* Вычисляет когда в следующий раз случится периодическое событие
*
* @return {Date}
*/
Event.prototype.getNextHappenDate = function () {
'use strict';
var nhd, today;
if (!this.nextHappenDate) {
today = new Date();
nhd = this.startDate;
while (nhd < today) {
nhd = Utils.addDateTime(nhd, this.repeat.value);
}
this.nextHappenDate = nhd;
}
return this.nextHappenDate;
};
/**
* Вычисляет следующее время напоминания для периодических событий
*
* @param {Event} event Событие
*
* @return {Date}
*/
Event.prototype.getNextAlarmTime = function () {
'use strict';
var nhd = this.getNextHappenDate();
return Utils.addDateTime(nhd, this.alert.value);
};
/**
* Функция проверяет, нужно ли напомнить о событии
*
* @param {Event} event Событие
*
* @return {Boolean}
*/
Event.prototype.isAlertTime = function () {
'use strict';
var today, diff;
today = new Date();
diff = today - this.getNextAlarmTime();
return diff > -500 && diff < 500;
};
Loading