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

Выборки по предикатам из задания 3 при помощи наследования #12

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
67 changes: 67 additions & 0 deletions Base/Collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Возвращает объект Collection
*
* @param {Array} items Элементы списка
*
* @example Collection([]);
*/
var Collection = function (items) {
"use strict";

this.items = items.slice(0);
Copy link
Member

Choose a reason for hiding this comment

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

Такое клонирование будет работать только с примитивами.

var a = {};
var b = [a];
var c = b.slice(0);

c[0] === a; // true

};

/**
* Добавление элемента в коллекцию
*
* @return {Collection}
*/
Collection.prototype.add = function (model) {
"use strict";

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

/**
* @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) {
"use strict";

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

/**
* @param {String} fieldName
*
* @see http://javascript.ru/Array/sort
*
* @example
* new Collection([]).sortBy("raiting");
* @return {Collection}
*/
Collection.prototype.sortBy = function (fieldName) {
"use strict";

var result = new this.constructor(this.items);
result.items.sort(function (first, second) {
if (first.get(fieldName) < second.get(fieldName)) {
return -1;
}
if (first.get(fieldName) > second.get(fieldName)) {
return 1;
}
return 0;
});
return result;
};
33 changes: 33 additions & 0 deletions Base/Model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var Model = function (data) {
"use strict";
};

/**
* @param {Object} attributes
*
* @example
* item.set({title: "March 20", content: "In his eyes she eclipses..."});
*/
Model.prototype.set = function (attributes) {
"use strict";
var keyName;
for (keyName in attributes) {
this[keyName] = attributes[keyName];
}
};

/**
* @param {String} attribute
*/
Model.prototype.get = function (attribute) {
"use strict";
return this[attribute];
};

/**
* @param {Object} attributes
*/
Model.prototype.validate = function (attributes) {
"use strict";
throw new Error('this is Abstract method');
};
79 changes: 79 additions & 0 deletions Event/Event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Возвращает объект Event
*
* @param {String} [name = "Событие"] Имя события
* @param {String} [address = ""] Адресс события
* @param {Object} time Дата события
* @param {Array} member Участники
* @param {Number} [raiting=3] Важность события (по шкале от 0 до 5)
*
* @example
* Event(
* "Совещание", "Екатеринбург, ул. Тургенева, д. 4, ауд. 150",
* EventTime(new Date(2011, 10, 10, 14, 48, 00), 60), ["я"], 5)
*
* @see EventTime
*/

var Event = function (name, address, time, member, raiting) {
"use strict";

Model.call(this);
var myTime = time || new EventTime(new Date(), 60);

this.set({
name: name || "Событие",
address: address || "",
timeStart: myTime.start,
timeLength: myTime.length,
Copy link
Member

Choose a reason for hiding this comment

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

Табы + пробелы?

member: member || [],
raiting: +raiting || 3
});
}

Event.prototype = {
__proto__: Model.prototype
Copy link
Member

Choose a reason for hiding this comment

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

Это не будет работать во многих браузерах. Лучше наследуй через оператор new и inherits() (см слайды лекции)

};


/**
* Возвращает объект EventTime
*
* @private
* @param {Number|Date} start Начало события
* @param {Number} [length=0] Длительность события в минутрах
*
* @example
* EventTime(new Date(2011, 10, 10, 14, 48, 00), 60)
*
* @return {Object}
*/
function EventTime(start, length) {
"use strict";

return {
"start": +start,
"length": +length || 0
};
}

/**
* Валидация собития
*
* @return {Array} Список ошибок
*/
Event.prototype.validate = function () {
"use strict";

var errors = [];
if (this.get("timeLength") < 0) {
errors.push("Продолжительность события меньше допустимой величины");
}
if (this.get("raiting") < 0) {
errors.puch("Рэйтинг собития меньше допустимой величины");
}
else if (this.get("raiting") > 5) {
errors.push("Рэйтинг события больше допустимой величины");
}
return errors;
};
136 changes: 136 additions & 0 deletions Event/Events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* @return {Object} Список событий
*/
var Events = function (items) {
"use strict";

Collection.call(this, items);
};

Events.prototype = {
__proto__: Collection.prototype
}
Events.prototype.constructor = Events;

/**
* Прошедшие события
*
* @return {Events}
*/
Events.prototype.findPastEvents = function () {
"use strict";

return this.filter(function (event) {
return event.get("timeStart") < new Date().getTime();
});
};

/**
* Предстоящие события
*
* @return {Events}
*/
Events.prototype.findFutureEvents = function () {
"use strict";

return this.filter(function (event) {
return event.get("timeStart") > new Date().getTime();
});
};

/**
* События с участием персоны с именем "name"
*
* @param personName Имя персоны
*
* @return {Events}
*/
Events.prototype.findEventsWithPerson = function (personName) {
"use strict";

return this.filter(function (event) {
return event.get("member").some(function (member) {
return member === personName;
});
});
};

/**
* События без участия персоны с именем "name"
*
* @param personName Имя персоны
*
* @return {Events}
*/
Events.prototype.findEventsWithoutPerson = function (personName) {
"use strict";

return this.filter(function (event) {
return event.get("member").every(function (member) {
return member != personName;
});
});
};

/**
* События, которые произойдут после указанного времени
*
* @param time Временной отсчет
*
* @return {Events}
*/
Events.prototype.findEventsHappendLaterTime = function (time) {
"use strict";

return this.filter(function (event) {
return event.get("timeStart") > time;
});
};

/**
* События, которые произойдут до указанного времени
*
* @param time Временной отсчет
*
* @return {Events}
*/
Events.prototype.findEventsHappendBeforeTime = function (time) {
"use strict";

return this.filter(function (event) {
return event.get("timeStart") < time;
});
};

/**
* Сортировка по времени начала события
*
* @return {Events}
*/
Events.prototype.sortEventsByDate = function () {
"use strict";

return this.sortBy("timeStart");
};

/**
* Сортировка по рэтингу события
*
* @return {Events}
*/
Events.prototype.sortEventsByRaiting = function () {
"use strict";

return this.sortBy("raiting");
};

/**
* Сортировка по имени события
*
* @return {Events}
*/
Events.prototype.sortEventsByName = function () {
"use strict";

return this.sortBy("name");
};
Loading