From fad05756b0bde52cf470e5b85984bb4b69494d04 Mon Sep 17 00:00:00 2001 From: Sergey Zhigalov Date: Wed, 7 Nov 2012 17:56:51 +0600 Subject: [PATCH 1/4] =?UTF-8?q?=D0=A3=D0=BD=D0=B0=D1=81=D0=BB=D0=B5=D0=B4?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BB=20Event=20=D0=BE=D1=82=20Model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Инициализация полей пока только через set --- Collection.js | 24 ++++++++ ComplexFunctions.js | 40 +++++++++++++ Event.js | 92 ++++++++++++++++++++++++++++++ Model.js | 27 +++++++++ SelectionFunctions.js | 127 ++++++++++++++++++++++++++++++++++++++++++ index.html | 17 ++++++ 6 files changed, 327 insertions(+) create mode 100644 Collection.js create mode 100644 ComplexFunctions.js create mode 100644 Event.js create mode 100644 Model.js create mode 100644 SelectionFunctions.js create mode 100644 index.html diff --git a/Collection.js b/Collection.js new file mode 100644 index 0000000..f57c309 --- /dev/null +++ b/Collection.js @@ -0,0 +1,24 @@ +var Collection = function (items) { + +}; + +/** + * @return {Collection} + */ +Collection.prototype.add = function (model) {}; +/** + * @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) {}; +/** + * @return {Collection} + */ +Collection.prototype.sortBy = function (fieldName) {}; \ No newline at end of file diff --git a/ComplexFunctions.js b/ComplexFunctions.js new file mode 100644 index 0000000..3a417bc --- /dev/null +++ b/ComplexFunctions.js @@ -0,0 +1,40 @@ +/** +* Все предстоящие события с моим участием отсортированные по рейтигу +*/ +function NewEventWithMeSortByRaiting() { + "use strict"; + events + .filter(NewEvent) + .filter(EventWithPerson, {name: "я"}) + .sort(SortByRaiting) + .forEach(PrintEvent); +} + +/** +* Все события, которые произойдут на этой неделе, отсортированые по рейтингу +*/ +function ThisWeekSortedByRaiting() { + "use strict"; + var now = new Date(); + var today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + var timeToEndOfWeek = (7 - now.getDay()) * 24 * 60 * 60 * 1000; + var endOfWeek = new Date(today + timeToEndOfWeek); + events + .filter(NewEvent) + .filter(BeforeTimeEvent, { time: endOfWeek }) + .sort(SortByRaiting) + .forEach(PrintEvent); +}; + +/** +* Выбрать ближайшее (по времени) событие без моего участия +*/ +function FirstEventWithoutMe() { + "use strict"; + var filteredEvents = events + .filter(NewEvent) + .filter(EventWithoutPerson, { name: "я" }) + .sort(SortByDate); + if (filteredEvents.length != 0) + PrintEvent(filteredEvents[0]); +}; \ No newline at end of file diff --git a/Event.js b/Event.js new file mode 100644 index 0000000..e4f1a9d --- /dev/null +++ b/Event.js @@ -0,0 +1,92 @@ +/** +* Возвращает объект 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) +* +* @return {Object} +* @see EventTime +*/ + +function CreateEvent(name, address, time, member, raiting) { + "use strict"; + return { + "name": name || "Событие", + "address": address.toString(), + "time": time, + "member": member || [], + "raiting": +raiting || 3 + }; +} + + +/** +* Возвращает объект 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 + }; +} + +var events = [ + CreateEvent("jsy6on0kz4", "7429kpz7nh", EventTime(new Date(2012, 10, 8), 45), ["Иванов", "я", "Петров"]), // 1 + CreateEvent("l8zklfh2r5", "1ygb121nee", EventTime(new Date(2012, 11, 22), 45), ["Иванов", "я"]), // 2 + CreateEvent("weoua5w3pf", "icu620fqpo", EventTime(new Date(2012, 11, 3), 45), ["Иванов"]), // 3 + CreateEvent("5zs4x4aij9", "4x9pkek4dp", EventTime(new Date(2012, 9, 10), 45), ["Иванов", "я", "Петров"]), // 4 + CreateEvent("s1m5vkm5mv", "5v6hifv041", EventTime(new Date(2012, 11, 25)), ["Иванов", "я"]), // 5 + CreateEvent("3bdg49u3ez", "zwvyu91w3b", EventTime(new Date(2012, 10, 10), 45), ["Иванов", "Петров"]), // 6 + CreateEvent("efc7dr20dx", "u641l89gw7", EventTime(new Date(2012, 9, 9)), ["Иванов", "я"]), // 7 + CreateEvent("pqlv9jglxq", "nkb24jd7u6", EventTime(new Date(2012, 10, 29)), ["Петров"]), // 8 + CreateEvent("iei2z6c63b", "kgzdrcs4mk", EventTime(new Date(2012, 11, 9)), ["я", "Петров"]), // 9 + CreateEvent("kygauxe4ub", "br0vzaikwr", EventTime(new Date(2012, 11, 27), 45), ["Иванов", "я"], 5), // 10 + CreateEvent("ke4vd03xp8", "9k3bbogzz5", EventTime(new Date(2012, 11, 3), 45), ["Иванов"]), // 11 + CreateEvent("jt4kew1ayg", "4q51wfulmd", EventTime(new Date(2012, 11, 29), 45), ["Иванов", "Петров"]), // 12 + CreateEvent("dg9q72wmw9", "c5r5t5z024", EventTime(new Date(2012, 11, 8), 45), ["Иванов"]), // 13 + CreateEvent("v4873m9tgp", "l0rdqy22d3", EventTime(new Date(2012, 10, 25), 45), ["Иванов", "я"]), // 14 + CreateEvent("rrb6bjyubc", "0oxvmk59p4", EventTime(new Date(2012, 10, 23)), ["Иванов", "я"]), // 15 + CreateEvent("0oqqd4j655", "rb1gc65t8d", EventTime(new Date(2012, 10, 11), 45), ["Иванов", "Петров"]), // 16 + CreateEvent("f7b16x9cmy", "ncxmyqnhp1", EventTime(new Date(2012, 11, 4)), ["Иванов", "я"]), // 17 + CreateEvent("ik3xyzqoky", "3cguxe6l6n", EventTime(new Date(2012, 11, 16)), ["Петров"]), // 18 + CreateEvent("u4mfqatngu", "a7vnsmnpb0", EventTime(new Date(2012, 9, 24)), ["я"]), // 19 + CreateEvent("s53m0j6u9j", "bk9y4szr2s", EventTime(new Date(2012, 9, 7), 45), ["Иванов", "я"], 5), // 20 + CreateEvent("lkajbmx7y2", "vwzpu1xl0o", EventTime(new Date(2012, 9, 20), 45), ["Иванов", "я", "Петров"], 1)//21 +]; + +var Event = function (arguments) { + Model.apply(this, arguments); +}; +Event.prototype = { + __proto__: Model.prototype +}; + +/** + * @param {Object} attributes + */ +Event.prototype.validate = function (attributes) { + if (!attributes.time) { + return "Time can't be null"; + } +}; + +var modelEvents = new Event(CreateEvent("jsy6on0kz4", "7429kpz7nh", EventTime(new Date(2012, 10, 8), 45), ["Иванов", "я", "Петров"])); \ No newline at end of file diff --git a/Model.js b/Model.js new file mode 100644 index 0000000..780fe70 --- /dev/null +++ b/Model.js @@ -0,0 +1,27 @@ +var Model = function (attributes) { + for (var keyName in attributes) { + this[keyName] = attributes[keyName]; + } +}; + +/** + * @param {Object} attributes + * + * @example + * item.set({title: "March 20", content: "In his eyes she eclipses..."}); + */ +Model.prototype.set = function (attributes) { + for (var keyName in attributes) { + this[keyName] = attributes[keyName]; + } +}; +/** + * @param {String} attribute + */ +Model.prototype.get = function (attribute) { + return this[attribute]; +}; +/** + * @param {Object} attributes + */ +Model.prototype.validate = function (attributes) { throw new Error('this is Abstract method') }; diff --git a/SelectionFunctions.js b/SelectionFunctions.js new file mode 100644 index 0000000..aeba37b --- /dev/null +++ b/SelectionFunctions.js @@ -0,0 +1,127 @@ + +/** +* Прошедшее событие +* +* @param {Object} event Событие +* +* @return {Boolean} +*/ +function OldEvent(event) { + "use strict"; + return event.time.start < new Date().getTime(); +} + +/** +* Предстоящее событие +* +* @param {Object} event Событие +* +* @return {Boolean} +*/ +function NewEvent(event) { + "use strict"; + return event.time.start >= new Date().getTime(); +} + +/** +* Событие, в котором участвует человек с именем "name" +* +* @param {Object} event Событие +* +* @return {Boolean} +*/ +function EventWithPerson(event) { + "use strict"; + var name = this.name; + return event.member.some(function (member) { + return member === name; + }); +} + +/** +* Событие, в котором не участвует человек с именем "name" +* +* @param {Object} event Событие +* +* @return {Boolean} +*/ +function EventWithoutPerson(event) { + "use strict"; + var name = this.name; + return event.member.every(function (member) { + return member !== name; + }); +} + +/** +* События, которые произойдут через время, указанное в time +* +* @param {Object} event Событие +* +* @return {Boolean} +*/ +function LaterTimeEvent(event) { + "use strict"; + return event.time.start >= this.time; +} + +/** +* События, которые произойдут до времени, указанного в time +* +* @param {Object} event Событие +* +* @return {Boolean} +*/ +function BeforeTimeEvent(event) { + "use strict"; + return event.time.start < this.time; +} + +/** +* Сортировка по времени события +* +* @param {Object} first Событие +* @param {Object} second Событие +* +* @return {Int} +*/ +function SortByDate(first, second) { + "use strict"; + if (first.time.start < second.time.start) { + return -1; + } + if (first.time.start > second.time.start) { + return 1; + } + return 0; +} + +/** +* Сортировка по рейтингу события +* +* @param {Object} first Событие +* @param {Object} second Событие +* +* @return {Int} +*/ +function SortByRaiting(first, second) { + "use strict"; + if (first.raiting < second.raiting) { + return 1; + } + if (first.raiting > second.raiting) { + return -1; + } + return 0; +} + +/** +* Напечатать событие +* +* @param {Object} event Событие +* +*/ +function PrintEvent(event) { + "use strict"; + console.log(event.name + " " + event.address + "; Begin in \"" + new Date(event.time.start) + "\". " + event.member.length + " member(s). Raiting: " + event.raiting); +} \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..73abcb1 --- /dev/null +++ b/index.html @@ -0,0 +1,17 @@ + + + + Выборки + + + + + + +

Выбрать все предстоящие события с моим участием отсортированные по рейтигу

+

Выбрать все события, которые произойдут на этой неделе, отсортированые по рейтингу

+

Выбрать ближайшее (по времени) событие без моего участия

+ +

Выбрать ближайшее (по времени) событие без моего участия

- \ No newline at end of file From 32081f171ca98bf98c4270d9784de130c87cf8a8 Mon Sep 17 00:00:00 2001 From: Sergey Zhigalov Date: Mon, 19 Nov 2012 09:26:35 +0600 Subject: [PATCH 3/4] Fixed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit У меня не получилось применить apply(), только call() но есть ощущение что делается именно то что нужно. --- Base/Collection.js | 67 ++++++++++++++++++ Model.js => Base/Model.js | 2 +- Collection.js | 24 ------- ComplexFunctions.js | 40 ----------- Event.js => Event/Event.js | 53 ++++++++++----- Event/Events.js | 136 +++++++++++++++++++++++++++++++++++++ Event/Example.js | 77 +++++++++++++++++++++ SelectionFunctions.js | 127 ---------------------------------- index.html | 11 ++- 9 files changed, 321 insertions(+), 216 deletions(-) create mode 100644 Base/Collection.js rename Model.js => Base/Model.js (90%) delete mode 100644 Collection.js delete mode 100644 ComplexFunctions.js rename Event.js => Event/Event.js (52%) create mode 100644 Event/Events.js create mode 100644 Event/Example.js delete mode 100644 SelectionFunctions.js diff --git a/Base/Collection.js b/Base/Collection.js new file mode 100644 index 0000000..cbcc2b1 --- /dev/null +++ b/Base/Collection.js @@ -0,0 +1,67 @@ +/** +* Возвращает объект Collection +* +* @param {Array} items Элементы списка +* +* @example Collection([]); +*/ +var Collection = function (items) { + "use strict"; + + this.items = items.slice(0); +}; + +/** + * Добавление элемента в коллекцию + * + * @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; +}; \ No newline at end of file diff --git a/Model.js b/Base/Model.js similarity index 90% rename from Model.js rename to Base/Model.js index 59ebf9f..5f38f1d 100644 --- a/Model.js +++ b/Base/Model.js @@ -1,4 +1,4 @@ -var Model = function () { +var Model = function (data) { "use strict"; }; diff --git a/Collection.js b/Collection.js deleted file mode 100644 index f57c309..0000000 --- a/Collection.js +++ /dev/null @@ -1,24 +0,0 @@ -var Collection = function (items) { - -}; - -/** - * @return {Collection} - */ -Collection.prototype.add = function (model) {}; -/** - * @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) {}; -/** - * @return {Collection} - */ -Collection.prototype.sortBy = function (fieldName) {}; \ No newline at end of file diff --git a/ComplexFunctions.js b/ComplexFunctions.js deleted file mode 100644 index 3a417bc..0000000 --- a/ComplexFunctions.js +++ /dev/null @@ -1,40 +0,0 @@ -/** -* Все предстоящие события с моим участием отсортированные по рейтигу -*/ -function NewEventWithMeSortByRaiting() { - "use strict"; - events - .filter(NewEvent) - .filter(EventWithPerson, {name: "я"}) - .sort(SortByRaiting) - .forEach(PrintEvent); -} - -/** -* Все события, которые произойдут на этой неделе, отсортированые по рейтингу -*/ -function ThisWeekSortedByRaiting() { - "use strict"; - var now = new Date(); - var today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); - var timeToEndOfWeek = (7 - now.getDay()) * 24 * 60 * 60 * 1000; - var endOfWeek = new Date(today + timeToEndOfWeek); - events - .filter(NewEvent) - .filter(BeforeTimeEvent, { time: endOfWeek }) - .sort(SortByRaiting) - .forEach(PrintEvent); -}; - -/** -* Выбрать ближайшее (по времени) событие без моего участия -*/ -function FirstEventWithoutMe() { - "use strict"; - var filteredEvents = events - .filter(NewEvent) - .filter(EventWithoutPerson, { name: "я" }) - .sort(SortByDate); - if (filteredEvents.length != 0) - PrintEvent(filteredEvents[0]); -}; \ No newline at end of file diff --git a/Event.js b/Event/Event.js similarity index 52% rename from Event.js rename to Event/Event.js index fd7c1f4..407da74 100644 --- a/Event.js +++ b/Event/Event.js @@ -10,21 +10,31 @@ * @example * Event( * "Совещание", "Екатеринбург, ул. Тургенева, д. 4, ауд. 150", -* EventTime(new Date(2011, 10, 10, 14, 48, 00), 60), -* ["Жигалов Сергей Алексеевич"], 5) +* EventTime(new Date(2011, 10, 10, 14, 48, 00), 60), ["я"], 5) * * @see EventTime */ var Event = function (name, address, time, member, raiting) { "use strict"; - this.name = name || "Событие"; - this.address = address.toString(); - this.time = time; - this.member = member || []; - this.raiting = +raiting || 3; + + Model.call(this); + var myTime = time || new EventTime(new Date(), 60); + + this.set({ + name: name || "Событие", + address: address || "", + timeStart: myTime.start, + timeLength: myTime.length, + member: member || [], + raiting: +raiting || 3 + }); } +Event.prototype = { + __proto__: Model.prototype +}; + /** * Возвращает объект EventTime @@ -40,23 +50,30 @@ var Event = function (name, address, time, member, raiting) { */ function EventTime(start, length) { "use strict"; + return { "start": +start, "length": +length || 0 }; } -Event.prototype = { - __proto__: Model.prototype -}; - /** - * @param {Object} attributes + * Валидация собития + * + * @return {Array} Список ошибок */ -Event.prototype.validate = function (attributes) { - if (!attributes.time) { - return "Time can't be null"; - } -}; +Event.prototype.validate = function () { + "use strict"; -var modelEvents = new Event("jsy6on0kz4", "7429kpz7nh", EventTime(new Date(2012, 10, 8), 45), ["Иванов", "я", "Петров"]); \ No newline at end of file + 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; +}; \ No newline at end of file diff --git a/Event/Events.js b/Event/Events.js new file mode 100644 index 0000000..35934ad --- /dev/null +++ b/Event/Events.js @@ -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"); +}; \ No newline at end of file diff --git a/Event/Example.js b/Event/Example.js new file mode 100644 index 0000000..c3355d7 --- /dev/null +++ b/Event/Example.js @@ -0,0 +1,77 @@ +var myEvents = new Events([]) + .add(new Event("jsy6on0kz4", "7429kpz7nh", EventTime(new Date(2012, 10, 8), 45), ["Иванов", "я", "Петров"])) // 1 + .add(new Event("l8zklfh2r5", "1ygb121nee", EventTime(new Date(2012, 11, 22), 45), ["Иванов", "я"])) // 2 + .add(new Event("weoua5w3pf", "icu620fqpo", EventTime(new Date(2012, 11, 3), 45), ["Иванов"])) // 3 + .add(new Event("5zs4x4aij9", "4x9pkek4dp", EventTime(new Date(2012, 9, 10), 45), ["Иванов", "я", "Петров"])) // 4 + .add(new Event("s1m5vkm5mv", "5v6hifv041", EventTime(new Date(2012, 11, 25)), ["Иванов", "я"])) // 5 + .add(new Event("3bdg49u3ez", "zwvyu91w3b", EventTime(new Date(2012, 10, 10), 45), ["Иванов", "Петров"])) // 6 + .add(new Event("efc7dr20dx", "u641l89gw7", EventTime(new Date(2012, 9, 9)), ["Иванов", "я"])) // 7 + .add(new Event("pqlv9jglxq", "nkb24jd7u6", EventTime(new Date(2012, 10, 29)), ["Петров"])) // 8 + .add(new Event("iei2z6c63b", "kgzdrcs4mk", EventTime(new Date(2012, 11, 9)), ["я", "Петров"])) // 9 + .add(new Event("kygauxe4ub", "br0vzaikwr", EventTime(new Date(2012, 11, 27), 45), ["Иванов", "я"], 5)) // 10 + .add(new Event("ke4vd03xp8", "9k3bbogzz5", EventTime(new Date(2012, 11, 3), 45), ["Иванов"])) // 11 + .add(new Event("jt4kew1ayg", "4q51wfulmd", EventTime(new Date(2012, 11, 29), 45), ["Иванов", "Петров"])) // 12 + .add(new Event("dg9q72wmw9", "c5r5t5z024", EventTime(new Date(2012, 11, 8), 45), ["Иванов"])) // 13 + .add(new Event("v4873m9tgp", "l0rdqy22d3", EventTime(new Date(2012, 10, 25), 45), ["Иванов", "я"])) // 14 + .add(new Event("rrb6bjyubc", "0oxvmk59p4", EventTime(new Date(2012, 10, 23)), ["Иванов", "я"])) // 15 + .add(new Event("0oqqd4j655", "rb1gc65t8d", EventTime(new Date(2012, 10, 11), 45), ["Иванов", "Петров"])) // 16 + .add(new Event("f7b16x9cmy", "ncxmyqnhp1", EventTime(new Date(2012, 11, 4)), ["Иванов", "я"])) // 17 + .add(new Event("ik3xyzqoky", "3cguxe6l6n", EventTime(new Date(2012, 11, 16)), ["Петров"])) // 18 + .add(new Event("u4mfqatngu", "a7vnsmnpb0", EventTime(new Date(2012, 9, 24)), ["я"])) // 19 + .add(new Event("s53m0j6u9j", "bk9y4szr2s", EventTime(new Date(2012, 9, 7), 45), ["Иванов", "я"], 5)) // 20 + .add(new Event("lkajbmx7y2", "vwzpu1xl0o", EventTime(new Date(2012, 9, 20), 45), ["Иванов", "я", "Петров"], 1)); // 21 + +/** +* Все предстоящие события с моим участием отсортированные по рейтигу +*/ +function NewEventWithMeSortByRaiting() { + "use strict"; + + myEvents + .findFutureEvents() + .findEventsWithPerson("я") + .sortEventsByRaiting() + .items.forEach(printEvent); +} + +/** +* Все события, которые произойдут на этой неделе, отсортированые по рейтингу +*/ +function ThisWeekSortedByRaiting() { + "use strict"; + + var now = new Date(); + var today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + var timeToEndOfWeek = (7 - now.getDay()) * 24 * 60 * 60 * 1000; + var endOfWeek = new Date(today + timeToEndOfWeek); + myEvents + .findFutureEvents() + .findEventsHappendBeforeTime(endOfWeek) + .sortEventsByRaiting() + .items.forEach(printEvent); +}; + +/** +* Выбрать ближайшее (по времени) событие без моего участия +*/ +function FirstEventWithoutMe() { + "use strict"; + var filteredEvents = myEvents + .findFutureEvents() + .findEventsWithoutPerson("я") + .sortEventsByDate() + .items; + if (filteredEvents.length != 0) + printEvent(filteredEvents[0]); +}; + +var printEvent = function (event) { + console.log( + "Наименование: " + event.name + + " по адресу: " + event.address + + " начало в: " + event.timeStart + + " будет длится: " + event.timeLength + + " участники: " + event.member + + " рэйтинг: " + event.raiting + ); +} \ No newline at end of file diff --git a/SelectionFunctions.js b/SelectionFunctions.js deleted file mode 100644 index aeba37b..0000000 --- a/SelectionFunctions.js +++ /dev/null @@ -1,127 +0,0 @@ - -/** -* Прошедшее событие -* -* @param {Object} event Событие -* -* @return {Boolean} -*/ -function OldEvent(event) { - "use strict"; - return event.time.start < new Date().getTime(); -} - -/** -* Предстоящее событие -* -* @param {Object} event Событие -* -* @return {Boolean} -*/ -function NewEvent(event) { - "use strict"; - return event.time.start >= new Date().getTime(); -} - -/** -* Событие, в котором участвует человек с именем "name" -* -* @param {Object} event Событие -* -* @return {Boolean} -*/ -function EventWithPerson(event) { - "use strict"; - var name = this.name; - return event.member.some(function (member) { - return member === name; - }); -} - -/** -* Событие, в котором не участвует человек с именем "name" -* -* @param {Object} event Событие -* -* @return {Boolean} -*/ -function EventWithoutPerson(event) { - "use strict"; - var name = this.name; - return event.member.every(function (member) { - return member !== name; - }); -} - -/** -* События, которые произойдут через время, указанное в time -* -* @param {Object} event Событие -* -* @return {Boolean} -*/ -function LaterTimeEvent(event) { - "use strict"; - return event.time.start >= this.time; -} - -/** -* События, которые произойдут до времени, указанного в time -* -* @param {Object} event Событие -* -* @return {Boolean} -*/ -function BeforeTimeEvent(event) { - "use strict"; - return event.time.start < this.time; -} - -/** -* Сортировка по времени события -* -* @param {Object} first Событие -* @param {Object} second Событие -* -* @return {Int} -*/ -function SortByDate(first, second) { - "use strict"; - if (first.time.start < second.time.start) { - return -1; - } - if (first.time.start > second.time.start) { - return 1; - } - return 0; -} - -/** -* Сортировка по рейтингу события -* -* @param {Object} first Событие -* @param {Object} second Событие -* -* @return {Int} -*/ -function SortByRaiting(first, second) { - "use strict"; - if (first.raiting < second.raiting) { - return 1; - } - if (first.raiting > second.raiting) { - return -1; - } - return 0; -} - -/** -* Напечатать событие -* -* @param {Object} event Событие -* -*/ -function PrintEvent(event) { - "use strict"; - console.log(event.name + " " + event.address + "; Begin in \"" + new Date(event.time.start) + "\". " + event.member.length + " member(s). Raiting: " + event.raiting); -} \ No newline at end of file diff --git a/index.html b/index.html index 26115d2..0cc26fb 100644 --- a/index.html +++ b/index.html @@ -2,16 +2,15 @@ Выборки - - - - + + + + +

Выбрать все предстоящие события с моим участием отсортированные по рейтигу

Выбрать все события, которые произойдут на этой неделе, отсортированые по рейтингу

Выбрать ближайшее (по времени) событие без моего участия

- - \ No newline at end of file From af5d441885dd2291acc4240e2d03796019cdd174 Mon Sep 17 00:00:00 2001 From: Sergey Zhigalov Date: Mon, 19 Nov 2012 18:27:36 +0600 Subject: [PATCH 4/4] =?UTF-8?q?=D0=A7=D0=B5=D1=81=D1=82=D0=BD=D0=BE=D0=B5?= =?UTF-8?q?=20=D0=BA=D0=BB=D0=BE=D0=BD=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20+=20=D1=83=D0=BD=D0=B8=D0=B2=D0=B5=D1=80=D1=81?= =?UTF-8?q?=D0=B0=D0=BB=D1=8C=D0=BD=D0=BE=D0=B5=20=D0=BD=D0=B0=D1=81=D0=BB?= =?UTF-8?q?=D0=B5=D0=B4=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Base/Collection.js | 6 +++++- Base/Model.js | 10 +++++++++- Clone.js | 29 +++++++++++++++++++++++++++++ Event/Event.js | 35 +++++++++++++++++------------------ Event/Events.js | 4 +--- Inherits.js | 7 +++++++ index.html | 4 +++- 7 files changed, 71 insertions(+), 24 deletions(-) create mode 100644 Clone.js create mode 100644 Inherits.js diff --git a/Base/Collection.js b/Base/Collection.js index cbcc2b1..44943e3 100644 --- a/Base/Collection.js +++ b/Base/Collection.js @@ -8,7 +8,11 @@ var Collection = function (items) { "use strict"; - this.items = items.slice(0); + var i; + this.items = [] + for (i = 0; i < items.length; i++) { + this.items[i] = items[i].clone(); + } }; /** diff --git a/Base/Model.js b/Base/Model.js index 5f38f1d..20c780a 100644 --- a/Base/Model.js +++ b/Base/Model.js @@ -30,4 +30,12 @@ Model.prototype.get = function (attribute) { Model.prototype.validate = function (attributes) { "use strict"; throw new Error('this is Abstract method'); -}; \ No newline at end of file +}; + +Model.prototype.clone = function () { + var attr, temp = new this.constructor(); + for (attr in this) { + temp[attr] = clone(this.get(attr)); + } + return temp; +} \ No newline at end of file diff --git a/Clone.js b/Clone.js new file mode 100644 index 0000000..02cb9f4 --- /dev/null +++ b/Clone.js @@ -0,0 +1,29 @@ +function clone(obj) { + if (null == obj || "object" != typeof obj) { + return obj; + } + + if (obj instanceof Date) { + var copy = new Date(); + copy.setTime(obj.getTime()); + return copy; + } + + if (obj instanceof Array) { + var i, copy = []; + for (i = 0; i < obj.length; ++i) { + copy[i] = clone(obj[i]); + } + return copy; + } + + if (obj instanceof Object) { + var copy = {}; + for (var attr in obj) { + if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); + } + return copy; + } + + throw new Error("Unable to copy obj! Its type isn't supported."); +} \ No newline at end of file diff --git a/Event/Event.js b/Event/Event.js index 407da74..b6bfd6e 100644 --- a/Event/Event.js +++ b/Event/Event.js @@ -18,22 +18,21 @@ var Event = function (name, address, time, member, raiting) { "use strict"; - Model.call(this); + Model.call(this); var myTime = time || new EventTime(new Date(), 60); - + this.set({ - name: name || "Событие", - address: address || "", - timeStart: myTime.start, + name: name || "Событие", + address: address || "", + timeStart: myTime.start, timeLength: myTime.length, - member: member || [], - raiting: +raiting || 3 - }); + member: member || [], + raiting: +raiting || 3 + }); } -Event.prototype = { - __proto__: Model.prototype -}; +inherits(Event, Model); +Event.prototype.constructor = Event; /** @@ -65,15 +64,15 @@ function EventTime(start, length) { Event.prototype.validate = function () { "use strict"; - var errors = []; + var errors = []; if (this.get("timeLength") < 0) { errors.push("Продолжительность события меньше допустимой величины"); } - if (this.get("raiting") < 0) { + if (this.get("raiting") < 0) { errors.puch("Рэйтинг собития меньше допустимой величины"); - } - else if (this.get("raiting") > 5) { - errors.push("Рэйтинг события больше допустимой величины"); - } - return errors; + } + else if (this.get("raiting") > 5) { + errors.push("Рэйтинг события больше допустимой величины"); + } + return errors; }; \ No newline at end of file diff --git a/Event/Events.js b/Event/Events.js index 35934ad..b8f51ad 100644 --- a/Event/Events.js +++ b/Event/Events.js @@ -7,9 +7,7 @@ var Events = function (items) { Collection.call(this, items); }; -Events.prototype = { - __proto__: Collection.prototype -} +inherits(Events, Collection); Events.prototype.constructor = Events; /** diff --git a/Inherits.js b/Inherits.js new file mode 100644 index 0000000..3cc478b --- /dev/null +++ b/Inherits.js @@ -0,0 +1,7 @@ +function inherits (Constructor, SuperConstructor) { + "use strict"; + + var Temp = function () {}; + Temp.prototype = SuperConstructor.prototype; + Constructor.prototype = new Temp(); +} \ No newline at end of file diff --git a/index.html b/index.html index 0cc26fb..63dd66d 100644 --- a/index.html +++ b/index.html @@ -2,8 +2,10 @@ Выборки + + - +