Skip to content

Task 4 - вроде готов #6

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 17 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 = [email protected]:jquery/qunit.git
3 changes: 3 additions & 0 deletions .gitsubmodules
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
122 changes: 122 additions & 0 deletions Task/BaseEvent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*global Collection: true*/

/**
* Shell for "sql" operations with Array Events.
* @prototype {Collection}
* @constructor
* @method {pastEventBase} - Создает BaseEvent с пропущенными событиями
* @method {pastEventBase} - Создает BaseEvent с грядущими событиями
* @method {nowEventBase} - Создает BaseEvent с текущими событиями
* @method {withFriend} - Создает BaseEvent с событиями, в которых принимал участие определенный человек
* @method {getEventAfterDay} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через день
* @method {getEventAfterWeek} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через неделю
* @method {getEventAfterMonth} - Создает BaseEvent с грядущими событиями, которые наступят не раньше, чем через месяц
* @method {getEventFromPeriod} - Создает BaseEvent с событиями, которые лежат между двумы датами [fromDate, toDate]
* @method {getEventAfterMonth} - Создает BaseEvent с теми же событиями, но отсортированными по убыванию звезд
* @method {getEventAfterMonth} - Создает BaseEvent с теми же событиями, но отсортироваными по возрастанию даты
* @example - Смотри файл с тестами...
*/
function BaseEvent(events) {
"use strict";
Collection.call(this, events);
this.events = events;
}
BaseEvent.prototype = Object.create(Collection.prototype, {
constructor: {
value: BaseEvent,
enumerable: false,
writable: true,
configurable: true
}
});
//пропущенные, текущие, будущие события
BaseEvent.prototype.pastEventBase = function () {
"use strict";
var currentDate = new Date();
return this.filter(function (event) {
return event.end.getTime() < currentDate.getTime();
});
};
BaseEvent.prototype.nextEventBase = function () {
"use strict";
var currentDate = new Date();
return this.filter(function (event) {
return event.start.getTime() > currentDate.getTime();
});
};
BaseEvent.prototype.nowEventBase = function () {
"use strict";
var currentDate = new Date();
return this.filter(function (event) {
return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime());
});
};
//событие с участием друга (Друг отношение рефлексивное ^^)
BaseEvent.prototype.withFriend = function (myFriend) {
"use strict";
return this.filter(function (event) {
return event.parties.some(function (party) {
return party.name === myFriend.name;
});
});
};
// События через период времени день, неделя, месяц
BaseEvent.prototype.getEventAfterWeek = function () {
"use strict";
var currentDate = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000);
return this.filter(function (event) {
return event.start.getTime() > currentDate.getTime();
});
};
BaseEvent.prototype.getEventAfterDay = function () {
"use strict";
var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
return this.filter(function (event) {
return event.start.getTime() > currentDate.getTime();
});
};
BaseEvent.prototype.getEventAfterMonth = function () {
"use strict";
var currentDate = new Date();
if (currentDate.getMonth() === 11) {
currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay());
} else {
currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDay());
}
return this.filter(function (event) {
return event.start.getTime() > currentDate.getTime();
});
};
// События за период
BaseEvent.prototype.getEventFromPeriod = function (fromDate, toDate) {
"use strict";
return this.filter(function (event) {
return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime());
});
};
BaseEvent.prototype.sortByStars = function (ascending) {
"use strict";
var comparer = function compare(a, b) {
if (a.stars > b.stars) {
return -1;
}
if (a.stars < b.stars) {
return 1;
}
return 0;
};
return this.sortBy(comparer, ascending);
};
BaseEvent.prototype.sortByDate = function (ascending) {
"use strict";
var comparer = function compare(a, b) {
if (a.start.getTime() < b.start.getTime()) {
return -1;
}
if (a.start.getTime() > b.start.getTime()) {
return 1;
}
return 0;
};
return this.sortBy(comparer, ascending);
};
50 changes: 50 additions & 0 deletions Task/Collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*global Collection: true*/

/**
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

/**
 * @constructor
 * 
 * @param {String} data description
 *
 * ...
 */

* Creates an instance of Event.
*
* @param {data} - start elements of collection
* @field {items} - elements of collection
* @method {add} - add element in current collection and return it
* @method {filter} - filter elements of current collection and return it
* @method {sortBy} - sort elements of current collection and return it
*/
Collection = function (otherItems) {
Copy link
Member

Choose a reason for hiding this comment

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

var Collection =!

"use strict";
var item;
this.items = [];
for (item in otherItems) {
if (otherItems.hasOwnProperty(item)) {
this.items.push(otherItems[item]);
}
}
};
Collection.prototype.add = function (obj) {
"use strict";
var newEvents = this.items.concat([obj]);
return new Collection(newEvents);
};
Collection.prototype.filter = function (selector) {
"use strict";
var newItems = this.items.filter(selector);
return new Collection(newItems);
};
Collection.prototype.sortBy = function (comparator, isInvert) {
"use strict";
var newItems = [].concat(this.items);
if (newItems.length === 0) {
return [];
}
if (comparator) {
if (isInvert) {
newItems.sort(function (a, b) {
return -1 * comparator(a, b);
});
} else {
newItems.sort(comparator);
}
} else {
newItems.sort();
}
return new Collection(newItems);
};
39 changes: 39 additions & 0 deletions Task/Model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

/**
* Abstract class for Event
*
* @param {data} - start elements of collection
* @field {items} - elements of collection
* @method {get} - get value of field
* @method {set} - set attributes
* @method {validate} - validate <this>
*/
var Model = function (data) {
"use strict";
var nameField;
for (nameField in data) {
this[nameField] = data[nameField];
}
};
Model.prototype.set = function (attributes) {
"use strict";
var nameAttr;
for (nameAttr in attributes) {
if (attributes.hasOwnProperty(nameAttr)) {
if (typeof this[nameAttr] !== "undefined") {
this[nameAttr] = attributes[nameAttr];
}
}
}
};
Model.prototype.get = function (attribute) {
"use strict";
if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") {
return; //return undefined;
}
return this[attribute];
};
Model.prototype.validate = function () {
"use strict";
throw new Error('this is Abstract method');
};
89 changes: 89 additions & 0 deletions Task/event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*global Model: true*/
/**
* Creates an instance of Event.
*
* @prototype {Model}
* @param {data} - is start event
* @field {start} - is start event
* @field {end} - is end event
* @field {id} - is id
* @field {location} - location - is gps and name of event's place
* @field {participants} - participants - array of participants
* @field {stars} - is assess the importance of the event
* @field {cost} - is price for entry
* @method {setLocation} - is setter for location's field
* @method {leaveMark} - is setter for stars's field (0,1,2,3,4,5 - validate value)
*/
function Event(data) {
"use strict";
this.id = Math.random();
this.location = {
"gps": {x: 0, y: 0},
"nameLocation": "Earth"
};
this.stars = 0;
this.cost = 0;
this.parties = [];
Model.call(this, data);
this.validate(this);
this.setLocation(this.location);
this.leaveMark(this.stars);
}
Event.prototype = Object.create(Model.prototype, {
constructor: {
value: Event,
enumerable: false,
writable: true,
configurable: true
}
});
Event.prototype.dateValidator = function (date) {
"use strict";
if (Object.prototype.toString.call(date) === "[object Date]") {
if (!isNaN(date.getTime())) {
return true;
}
}
return false;
};
Event.prototype.setLocation = function (gps, name) {
"use strict";
if (typeof gps !== "undefined" && typeof gps.x !== "undefined" && typeof gps.y !== "undefined" && typeof name === "string") {
this.location.gps = gps;
this.location.nameLocation = name;
} else {
this.location = {
"gps" : {"x" : 0, "y" : 0},
"nameLocation" : "Earth"
};
}
};
Event.prototype.leaveMark = function (stars) {
"use strict";
if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) {
stars = 0;
}
if (stars > 5) {
stars = 5;
}
stars = (stars - (stars % 1)); //обрезаем дробную часть
this.stars = stars;
};
Event.prototype.validate = function (event) {
"use strict";
if (event.cost < 0) {
throw new Error("Цена за вход не может быть отрицательной");
}
if (!Array.isArray(event.parties)) {
throw new Error("Участники - это массив");
}
if (event.parties.some(function (party) {
return !party.name;
})
) {
throw new Error("У одного из участников нет поля <ИМЯ>");
}
if (event.end < event.start) {
throw new Error("Даты начала и конца перепутаны");
}
};
18 changes: 18 additions & 0 deletions Task/test/BaseEventTest.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="../../qunit/qunit/qunit.css" type="text/css" media="screen">
<script type="text/javascript" src="../../qunit/qunit/qunit.js"></script>
<script type="text/javascript" src="../model.js"></script>
<script type="text/javascript" src="../collection.js"></script>
<script type="text/javascript" src="../event.js"></script>
<script type="text/javascript" src="../baseEvent.js"></script>
<script type="text/javascript" src="./BaseEventTest.js"></script>
</head>
<body>
<h1 id="qunit-header">QUnit test env</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>
Loading