Skip to content
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

задание 4 #13

Open
wants to merge 2 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
100 changes: 100 additions & 0 deletions collection_and_events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Collection - абстрактная коллекция объектов
* Collection.prototype.add - добавление объекта в коллекцию
*
* Events - коллекция событий в календаре. Объект наследуется от Collection
*
* Event - объект события в календаре
* Event.prototype.validate - проверяет корректность полей объекта
* Events.prototype.filterToDate - возвращает предстоящие или прощедшие события в зависимости от входящего параметра flag
* Events.prototype.FilterToParty - возвращает события, в которых я принимаю/ не принимаю участие в зависимости от входящего параметра flag
* Events.prototype.sortToDate - сортирует события по дате
* function str2date(s) - преобразует строку в дату
*/
var Collection = function (elem) {
'use strict';
this.elem = [];
var key;
for (key in elem) {
this.elem.push(elem[key]);
}
};

Collection.prototype.add = function (model) {
'use strict';
var key;
if (model.length > 0) {
for (key in model) {
if (model[key].validate() === true) {
this.elem.push(model[key]);
}
}
} else {
if (model.validate() === true) {
this.elem.push(model);
}
}
};

var Events = function (items) {
"use strict";
Collection.apply(this, arguments);
};
inherits(Events, Collection);

Events.prototype.constructor = Events;

function str2date(s) {
"use strict";
var dateParts = s.split('.');
if (typeof dateParts[2] === 'string') {
return new Date(dateParts[2], dateParts[1], dateParts[0]);
}
if (typeof dateParts[2] === 'undefined') {
dateParts = s.split('-');
return new Date(dateParts[0], dateParts[1], dateParts[2]);
}
}

Events.prototype.filterToDate = function (flag) {
"use strict";
var result, collection;
collection = this.elem;
if (flag === -1) {
result = collection.filter(function (collection) {
var s = str2date(collection.start);
return s < new Date();
});
} else {
result = collection.filter(function (collection) {
var s = str2date(collection.start);
return s >= new Date();
});
}
return result;
};

Events.prototype.FilterToParty = function (flag) {
"use strict";
var result, collection;
collection = this.elem;
if (flag === -1) {
result = collection.filter(function (collection) {
return collection.party === "не участвую";
});
} else {
result = collection.filter(function (collection) {
return collection.party === "участвую";
});
}
return result;
};

Events.prototype.sortToDate = function () {
"use strict";
var collection = this.elem;
collection.sort(function (a, b) {
return str2date(a.start) > str2date(b.start) ? 1 : -1;
});
return collection;
};
76 changes: 76 additions & 0 deletions model_and_event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Model - абстрактный объект
* Model.prototype.set - устанавливает аттрибуты и значения атрибутов, в соответсвии с принятым в качестве параметра объектом
* Model.prototype.get - возвращает запрашиваемое свойство у объекта
* Model.prototype.validate - проверяет корректность полей объекта
*
* Event - объект события в календаре. Объект наследуется от Model
* Event.prototype.validate - проверяет корректность полей объекта
*
* function inherits(Constructor, SuperConstructor) - функция для чистого наследования
*/
var Model = function (attributes) {
"use strict";
var key;
for (key in attributes) {
if (attributes.hasOwnProperty(key)) {
this[key] = attributes[key];
}
}
};

Model.prototype.set = function (attributes) {
"use strict";
var key;
for (key in attributes) {
if (attributes.hasOwnProperty(key)) {
this[key] = attributes[key];
}
}
};

Model.prototype.get = function (attribute) {
"use strict";
if (this.hasOwnProperty(attribute)) {
return this[attribute];
}
return undefined;
};

Model.prototype.validate = function (attributes) {
"use strict";
throw new Error('this is Abstract method');
};

var Event = function (data) {
Copy link
Member

Choose a reason for hiding this comment

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

Принято делать так, чтобы у каждой сущности был отдельный файл. Event -> Event.js Model -> Model.js и т.п.

"use strict";
Model.apply(this, arguments);
this.name = this.name || "Встреча";
this.place = this.place || {};
this.info = this.info || {};
this.reminder = this.reminder || "За день до встречи";
this.type = this.type || "Работа";
this.party = this.party || "участвую";
};

function inherits(Constructor, SuperConstructor) {
"use strict";
var F = function () {};
F.prototype = SuperConstructor.prototype;
Constructor.prototype = new F();
}

inherits(Event, Model);

Event.prototype.validate = function () {
"use strict";
if (this.start === "undefined") {
console.log("starts is can not be null");
return "starts is can not be null";
}
if (this.end !== "undefined" && this.end < this.start) {
console.log("can't end before it starts");
return "can't end before it starts";
}
return true;
};
31 changes: 31 additions & 0 deletions test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
<head>
<title>Вывод информации о событиях</title>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<script src="model_and_event.js" type="text/javascript" ></script>
<script src="collection_and_events.js" type="text/javascript" ></script>
<script src="test.js" type="text/javascript" ></script>
<style type="text/css">
.l-level{
width: 500px;
margin: 0 auto;
padding-top: 200px;
}
.arr {width: 500px;}
.butt {position: relative; margin: 0 auto; width: 320px;}
Copy link
Member

Choose a reason for hiding this comment

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

Используй полные имена - button? вот butt это немного другое :) Аналогично с arr.

.butt input {
display: block;
float: left;
margin: 10px;
}
</style>
</head>
<body>
<div class="l-level">
Тестирование вывода информации в консоль
</div>
</form>
</div>
</body>
</html>
55 changes: 55 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Создается коллекция типа Events из объектов типа Event.
*
* В консоль выводится всевозможная информация об объектах в коллекции
*/
var allEvents = new Events();
var testEvent= new Event({"name": "Pewpe", "start": "11.12.2012", "end": "13.12.2012"});
var Work = new Event({
"name": "Совещание",
"start": "2012-10-10",
"end": "2012-10-10",
"place": "Луначарского 92, кб.31",
"info": "Будут обсуждаться вопросы...",
"reminder": "За день до встречи",
"party": "участвую"});
var NewYear = new Event({
"name": "Праздник",
"start": "2012-12-10",
"end": "2012-12-10",
"place": "Луначарского 92, кб.31",
"info": "Всем быть в костюмах...",
"reminder": "За неделю",
"type": "Отдых",
"party": "участвую"});
var study = new Event({
"name": "Конференция",
"start": "2012-11-24",
"end": "2012-11-24",
"place": "Луначарского 92, кб.31",
"info": "Анализ биологических последовательностей",
"type": "Дела",
"party": "участвую"});
var conf = new Event({
"name": "Конференция",
"start": "2012-12-08",
"end": "2012-12-08",
"place": "Луначарского 92, кб.31",
"info": "Матроиды и графы",
"reminder": "За день",
"type": "Дела",
"party": "не участвую"});
var Sport = new Event({
"name": "Дополнительные тренировки",
"start": "2012-12-10",
"end": "2012-12-12",
"place": "Луначарского 92, кб.31",
"info": "Ура! У вас есть возможность посетить дополнительные тренировки",
"reminder": "За час",
"type": "Отдых",
"party": "участвую"});

allEvents.add([Sport, conf, study, NewYear, Work]);
console.log('Встречи, отсортированные по дате:', allEvents.sortToDate());
console.log('Предстоящие события:', allEvents.filterToDate(1));
console.log('События в которых я участвую:', allEvents.FilterToParty(1));