Skip to content

Дз4 #7

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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "qunit"]
path = qunit
url = git://github.com/jquery/qunit.git
69 changes: 69 additions & 0 deletions collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
(function (exports) {
"use strict";

exports.Collection = function (items) {

this.items = [];
var key;

for (key in items) {
if (items.hasOwnProperty(key)) {
this.items.push(items[key]);
}
}
};

Collection.prototype.constructor = exports.Collection;

/**
* Добавляет в коллекцию объект
*
* @param {object} model
*
* @return {Collection} * @example
*
*/
Collection.prototype.add = function (model) {

var temp = new this.constructor(this.items);
temp.items.push(model);
return temp;
};

/**
* @param {Function} selector
*
* @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
*
* @example
* new Collection().filter(function (item) {
* return item.get('attendee').indexOf("me") !== -1;
* });
* @return {Collection}
*/
Collection.prototype.filter = function (selector) {

if (typeof selector !== "function") {
throw new Error('Argument must be function');
}

return new this.constructor(this.items.filter(selector));
};

/**
* Принимает функцию сортировки и сортирует на основе ее
*
* @param {function} selector
*
* @return {Collection} * @example
*
*/
Collection.prototype.sort = function (selector) {

if (typeof selector !== "function") {
throw new Error('Argument must be function');
}

return new this.constructor(this.items.sort(selector));
};
}(window));
81 changes: 81 additions & 0 deletions event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
(function (exports) {
"use strict";

function isDate(date) {

if (typeof date === 'undefined') {
return false;
}
if (typeof date.getMonth !== 'function') {
return false;
}
return true;
}

exports.inherits = function (constructor, superconstructor) {

var Func = function () { };

Func.prototype = superconstructor.prototype;
constructor.prototype = new Func();
}

exports.Event = function (data) {

Model.apply(this, arguments);
};

inherits(Event, Model);

/**
* Валидирует объект event, либо undefined, если в объекте отсутвуют обязательные поля
* eventObject{
* name - название события
* start - начало
* end - окончание
* location - место
* remindTime - за сколько минут до события напомнить
* description - описание
* }

* @param {object} obj Объект
* @example
* Event({
* name: "Пара по веб-технологиям",
* start: new Date("2012-10-20 10:00:00"),
* end: new Date("2012-10-20 12:50:00"),
* location: "5 этаж",
* remindTime: 10,
* description: "Взять бумагу и ручку, не брать бук!"
* })
*
* @return {Object}
*/
Event.prototype.validate = function () {

var remindTime = this.remindTime || 0;
this.raiting = this.raiting || 0;

if (!isDate(this.get("start"))) {
throw new Error('Field "start" must be Date format');
}

if (!isDate(this.end)) {
this.end = this.start;
}

if (this.end < this.start) {
this.end = this.start;
}

return {
"name": this.name || "(Нет темы)",
"start": this.start,
"end": this.end,
"location": this.location || "",
"remindTime": remindTime,
"description": this.description || "(отсутствует)",
"raiting": this.raiting
};
};
}(window));
125 changes: 125 additions & 0 deletions events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
(function (exports) {
"use strict";

exports.Events = function (data) {

Collection.apply(this, arguments);
};

inherits(Events, Collection);

Events.prototype.constructor = exports.Events;

/**
* Возвращает прошедшие события, из items отсортированной по дате начала
*
* @param {events} - коллекция объектов типа event
* @return {Collection} - коллекция объектов типа event
*/
Events.prototype.past = function () {

return this.filter(function (events) {
return events.start < new Date();
});
};

/**
* Возвращает предстоящие события,
* из items, отсортированной по дате начала
*
* @return {Collection} - коллекция объектов типа event
*/
Events.prototype.coming = function () {

return this.filter(function (events) {
return events.start > new Date();
});
};

/**
* Возвращает события, которые произойдут через опр период времени,
* из items, отсортированной по дате начала
*
* @param {number} days - период (в днях) времени
*
* @return коллекция объектов типа event
*/
Events.prototype.comeThrough = function (days) {

var now = new Date();
now.setDate(now.getDate() + days);

var result = this.coming()
.filter(function (events) {
return events.start < now;
});
Copy link
Member

Choose a reason for hiding this comment

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

Вот так более читаемо

var result = this.coming()
    .filter(function (events) {
        return events.start < now;
    });

return result;


return result;
};

Events.prototype.byEndTime = function () {

return this.sort(function (a, b) {
return a.end - b.end;
});
};

Events.prototype.byRaiting = function () {

return this.sort(function (a, b) {
return a.raiting - b.raiting;
});
};

Events.prototype.byStartTime = function () {

return this.sort(function (a, b) {
return a.start - b.start;
});
};

/**
* Возвращает события,из items отсортированной по дате начала по возр/убыв
* от старых обытий к новым / наоборот.
* По умолчанию сортирует в порядке возрастания
*
* @param {bool} isAscending - необязательный параметр - указывает порядок сортировки.
* при отсутсвии сортируется по возрастанию.
*
* @return {Collection} - Новый объект типа Collection
*/
Events.prototype.sortByTime = function (isAscending) {

isAscending = isAscending || false;

if (isAscending) {
return this
.byStartTime();
}
return this.byStartTime()
.reverse();
};

/**
* Возвращает события, из items, отсортированной по рейтингу по убыв/возрастанию
* от событий с более высоким рейтингом к самому низко приоритетному / наоборот.
* По умолчанию сортирует в порядке убывания
*
* @param {bool} isAscending - необязательный параметр - указывает порядок сортировки.
* при отсутствии сортируется по убыванию.
*
* @return {COllection} - Новый объект типа Collection
*/
Copy link
Member

Choose a reason for hiding this comment

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

Формат JSDoc не корректный - http://code.google.com/p/jsdoc-toolkit/wiki/TagReference

description
%new_line%
@param {Type} name description
@param {Type} name description
%new_line%
@return {Type} description
/**
 * Создает новый экземпляр Circle по диаметру.
 *
 * @param {number} d Диаметр окружности.
 *
 * @return {Circle} Новый объект Circle.
 */
Circle.fromDiameter = function (d) {
    return new Circle(d / 2);
};

Events.prototype.sortByRaiting = function (isAscending) {

isAscending = isAscending || false;

if (isAscending) {
return this
.byRaiting();
}
return this
.byRaiting()
.reverse();
};
Copy link
Member

Choose a reason for hiding this comment

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

Не закрыта IEFE; Events и все подобные не экспортируются. exports.Events = Events;

}(window));
23 changes: 23 additions & 0 deletions examples.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
var examples = [
{ name: "Пара по веб-технологиям", start: new Date("2012-10-20 10:00:00"), end: new Date("2012-10-20 12:50:00"), location: "5 этаж", remindTime: 10, description: "Взять бумагу и ручку, не брать бук!" },
{ name: "День зимы", start: new Date("2012-10-27 06:00:00"), end: new Date("2012-10-27 12:00:00"), location: "Скандинавия", description: "Кататься ^_^" },
{ name: "День инженера механика", start: new Date("2012-10-29 10:00:00"), end: new Date("2012-10-29 15:00:00"), location: "9 этаж", remindTime: 10 },
{ name: "День вегана", start: new Date("2012-11-1 10:00:00"), end: new Date("2012-10-1 23:00"), location: "Дома", description: "Be vegan =)" },
{ name: "День журналисты", start: new Date("2012-11-8 10:00:00"), location: "Китай", remindTime: 10, description: "Поздравить Олежу" },
{ name: "Всемирный день борьбы с диабетом", start: new Date("2012-11-14 12:00") },
{ name: "Международный день отказа от курения", start: new Date("2012-11-15 12:00"), description: "Поздравить Сашку)" },
{ name: "День защиты черных котов", start: new Date("2012-11-17 14:00:00"), location: "Италия", remindTime: 50, description: "Котэ" },
{ name: "Всемирный день туалетов", start: new Date("2012-11-19 15:00:00"), location: "МИр", description: "о_О" },
{ name: "День революции", start: new Date("2012-11-20 12:00:00"), location: "Мексика"},
{ name: "День сладостей", start: new Date("2012-10-20 15:00:00"), location: "США", remindTime: 10, description: "Приготовить вкусняшки" },
{ name: "Ерофеев день", start: new Date("2012-10-17 16:00:00"), location: "Россия", description: "Лисики" },
{ name: "Утиный фестиваль", start: new Date("2012-10-13 12:00:00"), location: "Италия", description: "Все в Италию!" },
{ name: "Дент ребенка", start: new Date("2012-10-12 14:00:00"), location: "Бразилия" },
{ name: "День физкультуры", start: new Date("2012-10-8 12:00:00"), location: "Япония"},
{ name: "Всемирный день животных", start: new Date("2012-10-4 12:00:00 ")},
{ name: "День сакэ в Японии", start: new Date("2012-10-1 14:00:00") },
{ name: "День моря", start: new Date("2012-09-27 15:00:00") },
{ name: "День комиксов", start: new Date("2012-09-25 15:00:00"), location: "США"},
{ name: "День почитания пожилых людей", start: new Date("2012-09-17 16:00:00")},
{ name: "Международный жень демократии", start: new Date("2012-09-15 17:00:00")}
];
62 changes: 62 additions & 0 deletions model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
(function (exports) {
"use strict";

/**
* Абстрактный конструктор, принимает объект и создает абстрактный объект для работы
*
* @param {Object} attributes
*
* @example
* item.set({title: "March 20", content: "In his eyes she eclipses..."});
*/
exports.Model = function (data) {

var key;

for (key in data) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
};


/**
* Сеттер - устанавливает аттрибуты и значения атрибутов, в соответсвии с принятым в качестве параметра объектом
*
* @param {Object} attributes
*
* @example
* item.set({title: "March 20", content: "In his eyes she eclipses..."});
*/
Model.prototype.set = function (attributes) {

var key;

for (key in attributes) {
if (attributes.hasOwnProperty(key)) {
this[key] = attributes[key];
}
}
};

/**
* Геттер - возвращает запрашиваемое свойство у объекта
*
* @param {Object} attributes
*/
Model.prototype.get = function (attribute) {

if (this.hasOwnProperty(attribute)) {
return this[attribute];
}

return undefined;
};
/**
* @param {Object} attributes
*/
Model.prototype.validate = function (attributes) {
throw new Error('this is Abstract method');
};
}(window));
1 change: 1 addition & 0 deletions qunit
Submodule qunit added at 515de7
Loading