From 8beb916cc9e3dcbe4f6ae41012f52c44ca997917 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 25 Oct 2012 22:58:09 +0600 Subject: [PATCH 01/16] Add submodule qunit.js and qunit.css --- .gitmodules | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..8a92de5 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,6 @@ +[submodule "qunit-1.10.0.js"] + path = qunit-1.10.0.js + url = git://github.com/ManginAlexander/dz-3-iterators-functions/Task/qunit-1.10.0.js +[submodule "qunit-1.10.0.css"] + path = qunit-1.10.0.css + url = git://github.com/ManginAlexander/dz-3-iterators-functions/qunit-1.10.0.css From 94fd6e96cfda279b3c9294dfacf915453a299645 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 25 Oct 2012 23:04:33 +0600 Subject: [PATCH 02/16] Revert "Add submodule qunit.js and qunit.css" This reverts commit 8beb916cc9e3dcbe4f6ae41012f52c44ca997917. --- .gitmodules | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 .gitmodules diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 8a92de5..0000000 --- a/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "qunit-1.10.0.js"] - path = qunit-1.10.0.js - url = git://github.com/ManginAlexander/dz-3-iterators-functions/Task/qunit-1.10.0.js -[submodule "qunit-1.10.0.css"] - path = qunit-1.10.0.css - url = git://github.com/ManginAlexander/dz-3-iterators-functions/qunit-1.10.0.css From 45e2b847386ba45847d138a25311c926bc13883a Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 25 Oct 2012 23:30:05 +0600 Subject: [PATCH 03/16] add submodule qunit --- .gitmodules | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/.gitmodules b/.gitmodules index 8a92de5..3d7b4de 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,9 @@ -[submodule "qunit-1.10.0.js"] - path = qunit-1.10.0.js - url = git://github.com/ManginAlexander/dz-3-iterators-functions/Task/qunit-1.10.0.js -[submodule "qunit-1.10.0.css"] - path = qunit-1.10.0.css - url = git://github.com/ManginAlexander/dz-3-iterators-functions/qunit-1.10.0.css +[submodule "qunit-1.10.0.js"] + path = qunit-1.10.0.js + url = git://github.com/ManginAlexander/dz-3-iterators-functions/Task/qunit-1.10.0.js +[submodule "qunit-1.10.0.css"] + path = qunit-1.10.0.css + url = git://github.com/ManginAlexander/dz-3-iterators-functions/qunit-1.10.0.css +[submodule "qunit"] + path = qunit + url = git://github.com/jquery/qunit.git From c856e5c7c37660a8df444cf4b81ea6479bbaca08 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 25 Oct 2012 23:31:45 +0600 Subject: [PATCH 04/16] Revert "add submodule qunit" This reverts commit 45e2b847386ba45847d138a25311c926bc13883a. --- .gitmodules | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.gitmodules b/.gitmodules index 3d7b4de..8a92de5 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ -[submodule "qunit-1.10.0.js"] - path = qunit-1.10.0.js - url = git://github.com/ManginAlexander/dz-3-iterators-functions/Task/qunit-1.10.0.js -[submodule "qunit-1.10.0.css"] - path = qunit-1.10.0.css - url = git://github.com/ManginAlexander/dz-3-iterators-functions/qunit-1.10.0.css -[submodule "qunit"] - path = qunit - url = git://github.com/jquery/qunit.git +[submodule "qunit-1.10.0.js"] + path = qunit-1.10.0.js + url = git://github.com/ManginAlexander/dz-3-iterators-functions/Task/qunit-1.10.0.js +[submodule "qunit-1.10.0.css"] + path = qunit-1.10.0.css + url = git://github.com/ManginAlexander/dz-3-iterators-functions/qunit-1.10.0.css From 80d3f2be91b5cca068c789a5a2a6088deff76a36 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Fri, 26 Oct 2012 00:51:52 +0600 Subject: [PATCH 05/16] Subs --- .gitsubmodules | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .gitsubmodules diff --git a/.gitsubmodules b/.gitsubmodules new file mode 100644 index 0000000..e737545 --- /dev/null +++ b/.gitsubmodules @@ -0,0 +1,3 @@ +[submodule "qunit"] + path = qunit + url = git://github.com/jquery/qunit.git \ No newline at end of file From 43cd684b1e5d4784b70687dc95d7b0dea854a189 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Mon, 29 Oct 2012 19:46:25 +0600 Subject: [PATCH 06/16] Start of work --- .gitmodules | 3 +++ qunit | 1 + 2 files changed, 4 insertions(+) create mode 100644 .gitmodules create mode 160000 qunit diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..f3fbb8d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "qunit"] + path = qunit + url = git@github.com:jquery/qunit.git diff --git a/qunit b/qunit new file mode 160000 index 0000000..4e03a4b --- /dev/null +++ b/qunit @@ -0,0 +1 @@ +Subproject commit 4e03a4b4e2335ea24720444e460b00d0a110dd29 From 9e86a1263501f6a424f391d9796acf5fb1e2f8cc Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Mon, 29 Oct 2012 19:48:06 +0600 Subject: [PATCH 07/16] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=81=D0=B2=D0=BE=D0=B9=20=D0=BA=D0=BE=D0=B4=20=D0=B8?= =?UTF-8?q?=D0=B7=20=D1=81=D1=82=D0=B0=D1=80=D0=BE=D0=B3=D0=BE=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/CreateEventTest.js | 14 ++ Task/EventLeaveMarkTest.js | 17 +++ Task/EventSetLocationTest.js | 25 ++++ Task/baseEvent.js | 115 ++++++++++++++ Task/baseEventTest.js | 239 ++++++++++++++++++++++++++++++ Task/event.js | 76 ++++++++++ Task/test/CreateEvent.html | 17 +++ Task/test/LeaveMark.html | 17 +++ Task/test/SetLocation.html | 17 +++ Task/test/trivialSqlCommands.html | 18 +++ 10 files changed, 555 insertions(+) create mode 100644 Task/CreateEventTest.js create mode 100644 Task/EventLeaveMarkTest.js create mode 100644 Task/EventSetLocationTest.js create mode 100644 Task/baseEvent.js create mode 100644 Task/baseEventTest.js create mode 100644 Task/event.js create mode 100644 Task/test/CreateEvent.html create mode 100644 Task/test/LeaveMark.html create mode 100644 Task/test/SetLocation.html create mode 100644 Task/test/trivialSqlCommands.html diff --git a/Task/CreateEventTest.js b/Task/CreateEventTest.js new file mode 100644 index 0000000..8c9858e --- /dev/null +++ b/Task/CreateEventTest.js @@ -0,0 +1,14 @@ +test('Create event', function () { + "use strict"; + var dateToString = function (currentTime) { + var month = currentTime.getMonth() + 1, day = currentTime.getDate(), year = currentTime.getFullYear(); + return month + "/" + day + "/" + year; + }, undefinedDate, testEvent = new Event(undefinedDate); + equal(dateToString(testEvent.start), dateToString(new Date())); + testEvent = new Event(); + equal(dateToString(testEvent.start), dateToString(new Date())); + testEvent = new Event(new Date(5), new Date(3)); + ok(testEvent.start.getTime() < testEvent.end.getTime()); + testEvent = new Event(new Date(1), new Date(2)); + ok(testEvent.start.getTime() < testEvent.end.getTime()); +}); \ No newline at end of file diff --git a/Task/EventLeaveMarkTest.js b/Task/EventLeaveMarkTest.js new file mode 100644 index 0000000..479a15d --- /dev/null +++ b/Task/EventLeaveMarkTest.js @@ -0,0 +1,17 @@ +test('Leave Mark', function () { + "use strict"; + var testEvent = Event(new Date(1), new Date(2), "Earth"); + testEvent.leaveMark("No number"); + equal(testEvent.stars, 0, 'Если звездочку передали в виде не числа, то 0'); + var undefinedVar; + testEvent.leaveMark(undefinedVar); + equal(testEvent.stars, 0, 'Если звездочку забыли объявить, то 0'); + testEvent.leaveMark(-1); + equal(testEvent.stars, 0, 'Звездочка не может быть меньше 0'); + testEvent.leaveMark(6); + equal(testEvent.stars, 5, 'Звездочка не может быть больше 5'); + testEvent.leaveMark(3); + equal(testEvent.stars, 3, '0-5 звездочка не изменяется, если целая'); + testEvent.leaveMark(3.124); + equal(testEvent.stars, 3, 'Звездочки - Int'); +}); \ No newline at end of file diff --git a/Task/EventSetLocationTest.js b/Task/EventSetLocationTest.js new file mode 100644 index 0000000..5e9bac4 --- /dev/null +++ b/Task/EventSetLocationTest.js @@ -0,0 +1,25 @@ +test('Set location',function () { + "use strict"; + var testEvent = Event(new Date(1), new Date(2), "Earth"),gps,name; + testEvent.setLocation(gps,""); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); + testEvent.setLocation("Not gps",""); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); + testEvent.setLocation({"x": 0,"y": 0},[]); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "Название места не строка => установить значения по умолчанию"); + testEvent.setLocation({"x": 1,"y": 2},"Moon"); + deepEqual(testEvent.location, { + "gps" : {"x": 1,"y": 2}, + "nameLocation" : "Moon" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); + +}); \ No newline at end of file diff --git a/Task/baseEvent.js b/Task/baseEvent.js new file mode 100644 index 0000000..489a47c --- /dev/null +++ b/Task/baseEvent.js @@ -0,0 +1,115 @@ +/** + * Shell for "sql" operations with Array Events. + * + * @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"; + this.events = events; + //пропущенные, текущие, будущие события + this.pastEventBase = function () { + var currentDate = new Date(), needs; + needs = this.events.filter(function (event) { + return event.end.getTime() < currentDate.getTime(); + }); + return new BaseEvent(needs); + }; + this.nextEventBase = function () { + var currentDate = new Date(), needs; + needs = this.events.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + return new BaseEvent(needs); + }; + this.nowEventBase = function () { + var currentDate = new Date(), needs; + needs = this.events.filter(function (event) { + return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime()); + }); + return new BaseEvent(needs); + }; + //событие с участием друга (Друг отношение рефлексивное ^^) + this.withFriend = function (myFriend) { + var needs = this.events.filter(function (event) { + return event.parties.some(function (party) { + return party.name === myFriend.name; + }); + }); + return new BaseEvent(needs); + }; + // События через период времени день, неделя, месяц + this.getEventAfterWeek = function () { + var currentDate = new Date(), needs; + currentDate = new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000); + needs = this.events.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + return new BaseEvent(needs); + }; + this.getEventAfterDay = function () { + var currentDate = new Date(), needs; + currentDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000); + needs = this.events.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + return new BaseEvent(needs); + }; + this.getEventAfterMonth = function () { + var currentDate = new Date(), needs; + if (currentDate.getMonth() === 11) { + currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay()); + } else { + currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDay()); + } + needs = this.events.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); + return new BaseEvent(needs); + }; + // События за период + this.getEventFromPeriod = function (fromDate, toDate) { + var needs = this.events.filter(function (event) { + return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); + }); + return new BaseEvent(needs); + }; + this.sortByStars = function () { + var events = this.events.slice(0), comparer; + comparer = function compare(a, b) { + if (a.stars > b.stars) { + return -1; + } + if (a.stars < b.stars) { + return 1; + } + return 0; + }; + events.sort(comparer); + return new BaseEvent(events); + }; + this.sortByDate = function () { + var events = this.events.slice(0), comparer; + 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; + }; + events.sort(comparer); + return new BaseEvent(events); + }; +} \ No newline at end of file diff --git a/Task/baseEventTest.js b/Task/baseEventTest.js new file mode 100644 index 0000000..e3257ce --- /dev/null +++ b/Task/baseEventTest.js @@ -0,0 +1,239 @@ +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global initTestBase: true*/ +module("test simple SQL"); +test('pastEventBase()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, pastEventbase; + Date = function () { + return new RealDate("September 13, 2012 12:00:00"); + }; + pastEventbase = testBase.pastEventBase(); + equal(pastEventbase.events.length, 2); + ok(pastEventbase.events.some(function (event) { + return event.id === 15; + })); + ok(pastEventbase.events.some(function (event) { + return event.id === 17; + })); + Date = RealDate; +}); +test('nextEventBase()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, nextEventBase; + Date = function () { + return new RealDate("November 1, 2012 12:00:00"); + }; + nextEventBase = testBase.nextEventBase(); + equal(nextEventBase.events.length, 2); + ok(nextEventBase.events.some(function (event) { + return event.id === 19; + })); + ok(nextEventBase.events.some(function (event) { + return event.id === 20; + })); + Date = RealDate; +}); +test('nowEventBase()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, nowEventbase; + Date = function () { + return new RealDate("September 13, 2012 12:00:00"); + }; + nowEventbase = testBase.nowEventBase(); + equal(nowEventbase.events.length, 1); + ok(nowEventbase.events.some(function (event) { + return event.id === 16; + })); + Date = RealDate; +}); +test('withFriend("Alexander.Mangin")', function () { + "use strict"; + var testBase = initTestBase(), eventWithFriendBase = testBase.withFriend({name: "Alexander.Mangin"}); + equal(eventWithFriendBase.events.length, 1); + ok(eventWithFriendBase.events.some(function (event) { + return event.id === 16; + })); +}); +test('getEventAfterMonth()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, eventAfterMonthbase; + Date = function (param1, param2, param3) { + if (param1 && param2 && param3) { + return new RealDate(param1, param2, param3); + } + return new RealDate("October 1, 2012 12:00:00"); + }; + eventAfterMonthbase = testBase.getEventAfterMonth(); + equal(eventAfterMonthbase.events.length, 2); + ok(eventAfterMonthbase.events.some(function (event) { + return event.id === 19; + })); + ok(eventAfterMonthbase.events.some(function (event) { + return event.id === 20; + })); + Date = RealDate; +}); +test('getEventAfterDay()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, eventAfterDaybase; + Date = function (param1, param2, param3) { + if (param1 && param2 && param3) { + return new RealDate(param1, param2, param3); + } + return new RealDate("November 1, 2012 12:00:00"); + }; + eventAfterDaybase = testBase.getEventAfterDay(); + equal(eventAfterDaybase.events.length, 2); + ok(eventAfterDaybase.events.some(function (event) { + return event.id === 19; + })); + ok(eventAfterDaybase.events.some(function (event) { + return event.id === 20; + })); + Date = RealDate; +}); +test('getEventAfterWeek()', function () { + "use strict"; + var testBase = initTestBase(), RealDate = Date, eventAfterWeekbase; + Date = function (param1) { + if (param1) { + return new RealDate(param1); + } + return new RealDate("October 28, 2012 12:00:00"); + }; + eventAfterWeekbase = testBase.getEventAfterWeek(); + equal(eventAfterWeekbase.events.length, 1); + ok(eventAfterWeekbase.events.some(function (event) { + return event.id === 19; + })); + Date = RealDate; +}); +test('getEventFromPeriod(from,to)', function () { + "use strict"; + var testBase = initTestBase(), result; + result = testBase.getEventFromPeriod(new Date("September 12 2012 00:00:00"), new Date("September 14 2012 00:00:00")); + equal(result.events.length, 1); + ok(result.events.some(function (event) { + return event.id === 16; + })); +}); + +test('sortByStar()', function () { + "use strict"; + var testBase = initTestBase(), sortByStarsEventbase = testBase.sortByStars(); + equal(testBase.events.length, sortByStarsEventbase.events.length); + ok(sortByStarsEventbase.events[0].stars === 5); + ok(sortByStarsEventbase.events[1].stars === 5); +}); +test('sortByDate()', function () { + "use strict"; + var testBase = initTestBase(), sortByDateEventbase = testBase.sortByDate(); + equal(testBase.events.length, sortByDateEventbase.events.length); + ok(sortByDateEventbase.events[0].id === 15); + ok(sortByDateEventbase.events[1].id === 17); +}); +function initTestBase() { + "use strict"; + var bestOfSweetsDateStart = new Date("October 10, 2012 00:00:00"), + bestOfSweetsDateFinish = new Date("October 14, 2012 23:59:59"), + bestOfSweets = new Event(bestOfSweetsDateStart, bestOfSweetsDateFinish, "BestOfSweets", 1), + сirioDeNazareDateStart = new Date("October 8, 2012 00:00:00"), + сirioDeNazareDateFinish = new Date("October 15, 2012 23:59:59"), + сirioDeNazare = new Event(сirioDeNazareDateStart, сirioDeNazareDateFinish, "Cirio De Nazare", 2), + vinesDayDateStart = new Date("October 4, 2012 00:00:00"), + vinesDayDateFinish = new Date("October 6, 2012 23:59:59"), + vinesDay = new Event(vinesDayDateStart, vinesDayDateFinish, "День вина", 3), + theBlackCountryDateStart = new Date("October 31, 2012 00:00:00"), + theBlackCountryDateFinish = new Date("November 1, 2012 23:59:59"), + theBlackCountry = new Event(theBlackCountryDateStart, theBlackCountryDateFinish, 'Вкус "Черной страны"', 4), + oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), + oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), + oktoberFest = new Event(oktoberFestDateStart, oktoberFestDateFinish, 'OktoberFest', 5), + francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), + francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), + francfurtBook = new Event(francfurtBookDateStart, francfurtBookDateFinish, 'Франкфуртская международная книжная ярмарка', 6), + aidaDateStart = new Date("October 12, 2012 00:00:00"), + aidaDateFinish = new Date("October 27, 2012 23:59:59"), + aida = new Event(aidaDateStart, aidaDateFinish, '"Аида" у великих пирамид, Гиза', 7), + paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), + paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), + paradeOfLove = new Event(aidaDateStart, aidaDateFinish, 'Парад любви', 8), + sukkotDateStart = new Date("October 3, 2012 00:00:00"), + sukkotDateFinish = new Date("October 3, 2012 23:59:59"), + sukkot = new Event(aidaDateStart, aidaDateFinish, 'Парад любви', 9), + fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), + fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), + fishFestival = new Event(fishFestivalDateStart, fishFestivalDateStart, 'Фестиваль рыбы', 10), + chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), + chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), + chocolateFestival = new Event(fishFestivalDateStart, fishFestivalDateStart, 'Фестиваль "Еврошоколад"', 11), + digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), + digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), + digitalArtFestival = new Event(digitalArtFestivalDateStart, digitalArtFestivalDateFinish, 'Фестиваль цифрового исскуства', 12), + fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), + fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), + fatherDays = new Event(fatherDaysDateStart, fatherDaysDateFinish, 'Дни наследия', 13), + bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), + bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), + bearWeekend = new Event(bearWeekendDateStart, bearWeekendDateFinish, 'Bear Weekends', 14), + teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), + teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), + teaFestival = new Event(teaFestivalDateStart, teaFestivalDateFinish, 'Фестиваль Чая', 15), + programmerDayDateStart = new Date("September 13, 2012 00:00:00"), + programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), + programmerDay = new Event(programmerDayDateStart, programmerDayDateFinish, 'День программмиста', 16), + knowDayDateStart = new Date("September 1, 2012 00:00:01"), + knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), + knowDayDate = new Event(knowDayDateStart, knowDayDateDateFinish, 'День знаний', 17), + teacherDayDateStart = new Date("October 5, 2012 00:00:00"), + teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), + teacherDay = new Event(teacherDayDateStart, teacherDayDateFinish, 'День учителя', 18), + securiteDayDateStart = new Date("November 5, 2012 00:00:00"), + securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), + securiteDay = new Event(securiteDayDateStart, securiteDayDateFinish, 'День защиты информации', 19), + nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), + nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), + nationUnition = new Event(nationUnitionDateStart, nationUnitionDateDateFinish, 'День нароного единства', 20); + bestOfSweets.setLocation({gps :{x : 15, y : 189, name : "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"}}); + bestOfSweets.leaveMark(2); + сirioDeNazare.setLocation({gps :{x : 45, y : 133, name : "Бразилия, Белен, Фестиваль Cirio De Nazare"}}); + сirioDeNazare.leaveMark(1); + vinesDay.setLocation({gps :{x : 45, y : 133, name : "Венгрия, Мор, День вина"}}); + vinesDay.leaveMark(5); + theBlackCountry.setLocation({gps :{x : 45, y : 133, name : "Великобритания, Дадли, Вкус 'Черной страны'"}}); + theBlackCountry.leaveMark(3); + oktoberFest.setLocation({gps :{x : 45, y : 133, name : "Германия, Мюнхен, OktoberFest"}}); + oktoberFest.leaveMark(1); + programmerDay.parties = [{name: "Pupkin"}, {name: "Alex.IDontKnow"}]; + francfurtBook.setLocation({gps :{x : 45, y : 133, name : "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"}}); + francfurtBook.leaveMark(1); + aida.setLocation({gps :{x : 45, y : 133, name : "Египет, ?, Аида у великих пирамид, Гиза"}}); + aida.leaveMark(3); + paradeOfLove.setLocation({gps :{x : 45, y : 133, name : "Израль, Тель-Авиве, Парад любви"}}); + paradeOfLove.leaveMark(1); + sukkot.setLocation({gps :{x : 45, y : 133, name : "Израль, Иерусалиме, праздник Суккот"}}); + sukkot.leaveMark(4); + fishFestival.setLocation({gps :{x : 45, y : 133, name : "Испания, О Грове, Фестиваль рыбы"}}); + fishFestival.leaveMark(5); + chocolateFestival.setLocation({gps :{x : 45, y : 133, name : 'Италия, Перуджа, Фестиваль "Еврошоколад"'}}); + chocolateFestival.leaveMark(1); + digitalArtFestival.setLocation({gps :{x : 45, y : 133, name : "Австрия, Линц, Фестиваль Цифрового Исскуства"}}); + digitalArtFestival.leaveMark(3); + fatherDays.setLocation({gps :{x : 45, y : 133, name : "Бельгия, Антверпене, Дни наследия"}}); + fatherDays.leaveMark(4); + bearWeekend.setLocation({gps :{x : 45, y : 133, name : "Бельгия, Брюссель, Bear Weekends"}}); + bearWeekend.leaveMark(2); + teaFestival.setLocation({gps :{x : 45, y : 133, name : "Россия, Москва, Фестиваль чая"}}); + programmerDay.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День программиста"}}); + programmerDay.parties = [{name: "Alexander.Mangin"}, {name: "Alex.IDontKnow"}]; + knowDayDate.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День знаний"}}); + teacherDay.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День учителя"}}); + securiteDay.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День защиты информации"}}); + nationUnition.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День народного единства"}}); + return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook + , aida, paradeOfLove, sukkot, fishFestival, chocolateFestival, digitalArtFestival, fatherDays, + bearWeekend, teaFestival, programmerDay, knowDayDate, teacherDay, securiteDay, nationUnition]); +} \ No newline at end of file diff --git a/Task/event.js b/Task/event.js new file mode 100644 index 0000000..04021e2 --- /dev/null +++ b/Task/event.js @@ -0,0 +1,76 @@ +/** + * Creates an instance of Event. + * + * @param {start} - is start event + * @param {end} - is end event + * @param {location} - is location event + * @param {location} - is id + * @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 - допустимые значения) + */ +function Event(start, end, location, id) { + "use strict"; + var tempDate; + if (!Event.dateValidator(start)) { + start = new Date(); + } + if (!Event.dateValidator(end)) { + end = start; + } + if (start.getTime() > end.getTime()) { + tempDate = end; + end = start; + start = tempDate; + } + location = location || { + "gps": {x: 0, y: 0}, + "nameLocation": "Earth" + }; + id = id || Math.random(); + return { + "id": id, + "start": start, + "end": end, + "location": location, + "participants": [], + "stars": 0, + "cost": 0, + "parties": [], + "setLocation": function (gps, name) { + 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" + }; + } + }, + "leaveMark": function (stars) { + if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { + stars = 0; + } + if (stars > 5) { + stars = 5; + } + stars = (stars - (stars % 1)); //обрезаем дробную часть + this.stars = stars; + } + }; +} +Event.dateValidator = function (date) { + if (Object.prototype.toString.call(date) === "[object Date]") { + if (!isNaN(date.getTime())) { + return true; + } + } + return false; +} \ No newline at end of file diff --git a/Task/test/CreateEvent.html b/Task/test/CreateEvent.html new file mode 100644 index 0000000..edce7ef --- /dev/null +++ b/Task/test/CreateEvent.html @@ -0,0 +1,17 @@ + + + + + + + + + + + +

QUnit test env

+

+

+
    + + \ No newline at end of file diff --git a/Task/test/LeaveMark.html b/Task/test/LeaveMark.html new file mode 100644 index 0000000..57e74e6 --- /dev/null +++ b/Task/test/LeaveMark.html @@ -0,0 +1,17 @@ + + + + + + + + + + + +

    QUnit test env

    +

    +

    +
      + + \ No newline at end of file diff --git a/Task/test/SetLocation.html b/Task/test/SetLocation.html new file mode 100644 index 0000000..61df743 --- /dev/null +++ b/Task/test/SetLocation.html @@ -0,0 +1,17 @@ + + + + + + + + + + + +

      QUnit test env

      +

      +

      +
        + + \ No newline at end of file diff --git a/Task/test/trivialSqlCommands.html b/Task/test/trivialSqlCommands.html new file mode 100644 index 0000000..414d382 --- /dev/null +++ b/Task/test/trivialSqlCommands.html @@ -0,0 +1,18 @@ + + + + + + + + + + + + +

        QUnit test env

        +

        +

        +
          + + \ No newline at end of file From b5128d4029037022378958895f4879380dd336c4 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Mon, 29 Oct 2012 22:45:27 +0600 Subject: [PATCH 08/16] add abs Model, change link to qunit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1) В конструкторе клонируются все поля из переданного ему объекта //Todo Не уверен что так правильно.. стоит еще подумать 2) В set-ре устанавливается поля <=> 1. Поле у объекта существует 2. Значение поля отлично от undefined 3) В get-ре поле вовращается <=> 1. Оно существует у объекта 2. Имя поля имеет тип строку. --- Task/Model.js | 36 ++++++++++++++++++++++++++++++ Task/ModelTest.js | 32 ++++++++++++++++++++++++++ Task/test/CreateAbstractModet.html | 17 ++++++++++++++ Task/test/CreateEvent.html | 4 ++-- Task/test/LeaveMark.html | 4 ++-- Task/test/SetLocation.html | 4 ++-- Task/test/trivialSqlCommands.html | 4 ++-- 7 files changed, 93 insertions(+), 8 deletions(-) create mode 100644 Task/Model.js create mode 100644 Task/ModelTest.js create mode 100644 Task/test/CreateAbstractModet.html diff --git a/Task/Model.js b/Task/Model.js new file mode 100644 index 0000000..1d89e31 --- /dev/null +++ b/Task/Model.js @@ -0,0 +1,36 @@ +var Model = function (data) { + var nameField; + for(nameField in data) { + this[nameField] = data[nameField]; + } +}; +/** + * @param {Object} attributes + * + * @example + * item.set({title: "March 20", content: "In his eyes she eclipses..."}); + */ +Model.prototype.set = function (attributes) { + var nameAttr; + for(nameAttr in attributes) { + if(attributes.hasOwnProperty(nameAttr)) { + if (typeof this[nameAttr] !== "undefined") { + this[nameAttr] = attributes[nameAttr]; + } + } + } +}; +/** + * @param {String} attribute + */ +Model.prototype.get = function (attribute) { + if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { + return; //return undefined; + } + return this[attribute]; +}; +/** + * @param {Object} attributes + */ +Model.prototype.validate = function (attributes) {throw new Error('this is Abstract method')}; +// \ No newline at end of file diff --git a/Task/ModelTest.js b/Task/ModelTest.js new file mode 100644 index 0000000..2428410 --- /dev/null +++ b/Task/ModelTest.js @@ -0,0 +1,32 @@ +module("Create model") +test('Проверка конструктора клонирования', function () { + "use strict"; + var model = new Model(new TestObject(1)); + equal(typeof model["myNumber"], "number", "Личный объект не скопировался"); + equal(typeof model["commonNumber"], "number", "Объекты прототипа не скопировались"); +}); +test('Проверка метода get()', function () { + "use strict"; + var model = new Model(new TestObject(1)); + equal(model.get("commonNumber"),20,"Нет доступа к полям прототипа"); + equal(model.get("myNumber"),1,"Нет доступа к личным полям"); + equal(typeof model.get({}),"undefined","Объект не исполняет интерфейс"); + equal(typeof model.get("ТакогоПоляТочноНет"),"undefined","несуществующее поле определено"); +}); +test('Проверка метода set()', function () { + "use strict"; + var model = new Model(new TestObject(1)); + model.set({"myNumber": 2}); + equal(typeof model.get("myNumber"), "number", "Присваение произошло с ошибкой"); + equal(model.get("myNumber"), 2, "Присвоение произошло с ошибкой"); + model.set({"commonNumber":2}); + equal(TestObject.prototype.commonNumber, 20, "Присвоение испортило прототип"); + equal(model.get("commonNumber"), 2, "Ошибка при присвоении наследуемому полю через прототип"); +}); + +function TestObject (number) { + this.myNumber = number; + }; +TestObject.prototype.commonNumber = 20; + + diff --git a/Task/test/CreateAbstractModet.html b/Task/test/CreateAbstractModet.html new file mode 100644 index 0000000..78ae495 --- /dev/null +++ b/Task/test/CreateAbstractModet.html @@ -0,0 +1,17 @@ + + + + + + + + + + + +

          QUnit test env

          +

          +

          +
            + + \ No newline at end of file diff --git a/Task/test/CreateEvent.html b/Task/test/CreateEvent.html index edce7ef..44b256e 100644 --- a/Task/test/CreateEvent.html +++ b/Task/test/CreateEvent.html @@ -2,8 +2,8 @@ - - + + diff --git a/Task/test/LeaveMark.html b/Task/test/LeaveMark.html index 57e74e6..baaf6b2 100644 --- a/Task/test/LeaveMark.html +++ b/Task/test/LeaveMark.html @@ -2,8 +2,8 @@ - - + + diff --git a/Task/test/SetLocation.html b/Task/test/SetLocation.html index 61df743..56f64d8 100644 --- a/Task/test/SetLocation.html +++ b/Task/test/SetLocation.html @@ -2,8 +2,8 @@ - - + + diff --git a/Task/test/trivialSqlCommands.html b/Task/test/trivialSqlCommands.html index 414d382..1d5766c 100644 --- a/Task/test/trivialSqlCommands.html +++ b/Task/test/trivialSqlCommands.html @@ -2,8 +2,8 @@ - - + + From 2825e0d5061f544a9b0bd718d242bd34b3c25705 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Tue, 30 Oct 2012 19:09:57 +0600 Subject: [PATCH 09/16] =?UTF-8?q?=D0=9D=D0=B0=D1=81=D0=BB=D0=B5=D0=B4?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BB=D1=81=D1=8F=20=D0=BE=D1=82=20Model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/CreateEventTest.js | 10 +-- Task/EventLeaveMarkTest.js | 4 +- Task/EventSetLocationTest.js | 4 +- Task/Model.js | 3 +- Task/event.js | 127 ++++++++++++++++-------------- Task/test/CreateEvent.html | 1 + Task/test/LeaveMark.html | 2 + Task/test/SetLocation.html | 3 +- Task/test/trivialSqlCommands.html | 1 + 9 files changed, 85 insertions(+), 70 deletions(-) diff --git a/Task/CreateEventTest.js b/Task/CreateEventTest.js index 8c9858e..4ae6196 100644 --- a/Task/CreateEventTest.js +++ b/Task/CreateEventTest.js @@ -3,12 +3,10 @@ var dateToString = function (currentTime) { var month = currentTime.getMonth() + 1, day = currentTime.getDate(), year = currentTime.getFullYear(); return month + "/" + day + "/" + year; - }, undefinedDate, testEvent = new Event(undefinedDate); - equal(dateToString(testEvent.start), dateToString(new Date())); - testEvent = new Event(); - equal(dateToString(testEvent.start), dateToString(new Date())); - testEvent = new Event(new Date(5), new Date(3)); + }, currentTime = new Date(), testEvent = new Event({"start":currentTime}); + equal(dateToString(testEvent.start), dateToString(currentTime)); + testEvent = new Event({"start": new Date(2), "end": new Date(1)}); ok(testEvent.start.getTime() < testEvent.end.getTime()); - testEvent = new Event(new Date(1), new Date(2)); + testEvent = new Event({"start": new Date(1), "end": new Date(2)}); ok(testEvent.start.getTime() < testEvent.end.getTime()); }); \ No newline at end of file diff --git a/Task/EventLeaveMarkTest.js b/Task/EventLeaveMarkTest.js index 479a15d..65908dc 100644 --- a/Task/EventLeaveMarkTest.js +++ b/Task/EventLeaveMarkTest.js @@ -1,6 +1,6 @@ -test('Leave Mark', function () { +test('Leave Mark', function () { "use strict"; - var testEvent = Event(new Date(1), new Date(2), "Earth"); + var testEvent = new Event({}); testEvent.leaveMark("No number"); equal(testEvent.stars, 0, 'Если звездочку передали в виде не числа, то 0'); var undefinedVar; diff --git a/Task/EventSetLocationTest.js b/Task/EventSetLocationTest.js index 5e9bac4..16844e8 100644 --- a/Task/EventSetLocationTest.js +++ b/Task/EventSetLocationTest.js @@ -1,6 +1,6 @@ -test('Set location',function () { +test('Set location',function () { "use strict"; - var testEvent = Event(new Date(1), new Date(2), "Earth"),gps,name; + var testEvent = new Event({}),gps; testEvent.setLocation(gps,""); deepEqual(testEvent.location, { "gps" : {"x": 0,"y": 0}, diff --git a/Task/Model.js b/Task/Model.js index 1d89e31..711a467 100644 --- a/Task/Model.js +++ b/Task/Model.js @@ -32,5 +32,4 @@ Model.prototype.get = function (attribute) { /** * @param {Object} attributes */ -Model.prototype.validate = function (attributes) {throw new Error('this is Abstract method')}; -// \ No newline at end of file +Model.prototype.validate = function (attributes) {throw new Error('this is Abstract method')}; \ No newline at end of file diff --git a/Task/event.js b/Task/event.js index 04021e2..268f332 100644 --- a/Task/event.js +++ b/Task/event.js @@ -1,10 +1,7 @@ -/** +/** * Creates an instance of Event. * - * @param {start} - is start event - * @param {end} - is end event - * @param {location} - is location event - * @param {location} - is id + * @param {data} - is start event * @field {start} - is start event * @field {end} - is end event * @field {id} - is id @@ -15,62 +12,78 @@ * @method {setLocation} - is setter for location's field * @method {leaveMark} - is setter for stars's field (0,1,2,3,4,5 - допустимые значения) */ -function Event(start, end, location, id) { + +function Event(data) { "use strict"; - var tempDate; - if (!Event.dateValidator(start)) { - start = new Date(); - } - if (!Event.dateValidator(end)) { - end = start; + Model.call(this,data); + this.validate(); +} + + +(function () { + var inherits = function (Constructor, SuperConstructor) { + var tempConstructor = function () {}; + tempConstructor.prototype = SuperConstructor.prototype; + Constructor.prototype = new tempConstructor(); } - if (start.getTime() > end.getTime()) { - tempDate = end; - end = start; - start = tempDate; + + inherits(Event, Model); + + Event.prototype.dateValidator = function (date) { + if (Object.prototype.toString.call(date) === "[object Date]") { + if (!isNaN(date.getTime())) { + return true; + } + } + return false; } - location = location || { - "gps": {x: 0, y: 0}, - "nameLocation": "Earth" + Event.prototype.setLocation = function (gps, name) { + 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" + }; + } }; - id = id || Math.random(); - return { - "id": id, - "start": start, - "end": end, - "location": location, - "participants": [], - "stars": 0, - "cost": 0, - "parties": [], - "setLocation": function (gps, name) { - 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" - }; - } - }, - "leaveMark": function (stars) { - if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { - stars = 0; - } - if (stars > 5) { - stars = 5; - } - stars = (stars - (stars % 1)); //обрезаем дробную часть - this.stars = stars; + Event.prototype.leaveMark = function (stars) { + if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { + stars = 0; + } + if (stars > 5) { + stars = 5; } + stars = (stars - (stars % 1)); //обрезаем дробную часть + this.stars = stars; }; -} -Event.dateValidator = function (date) { - if (Object.prototype.toString.call(date) === "[object Date]") { - if (!isNaN(date.getTime())) { - return true; + Event.prototype.validate = function () { + var tempDate; + this.id = this.id || Math.random(); + this.location = this.location || { + "gps": {x: 0, y: 0}, + "nameLocation": "Earth" + }; + this.location = this.location || []; + this.stars = this.stars || 0; + this.cost = this.cost || 0; + this.parties =this.parties || []; + + if (!this.dateValidator(this.start)) { + this.start = new Date(); } - } - return false; -} \ No newline at end of file + if (!this.dateValidator(this.end)) { + this.end = this.start; + } + if (this.end < this.start) { + tempDate = this.start; + this.start = this.end; + this.end = tempDate; + } + this.setLocation(this.location); + this.leaveMark(this.stars); +} +}()); + + diff --git a/Task/test/CreateEvent.html b/Task/test/CreateEvent.html index 44b256e..9235784 100644 --- a/Task/test/CreateEvent.html +++ b/Task/test/CreateEvent.html @@ -4,6 +4,7 @@ + diff --git a/Task/test/LeaveMark.html b/Task/test/LeaveMark.html index baaf6b2..da075a3 100644 --- a/Task/test/LeaveMark.html +++ b/Task/test/LeaveMark.html @@ -4,7 +4,9 @@ + + diff --git a/Task/test/SetLocation.html b/Task/test/SetLocation.html index 56f64d8..2404f50 100644 --- a/Task/test/SetLocation.html +++ b/Task/test/SetLocation.html @@ -4,7 +4,8 @@ - + + diff --git a/Task/test/trivialSqlCommands.html b/Task/test/trivialSqlCommands.html index 1d5766c..bc091ae 100644 --- a/Task/test/trivialSqlCommands.html +++ b/Task/test/trivialSqlCommands.html @@ -5,6 +5,7 @@ + From 5d69c6ee7d5a43c825ee79807096188f927b5f53 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Wed, 31 Oct 2012 01:03:41 +0600 Subject: [PATCH 10/16] =?UTF-8?q?=D0=9A=D0=BE=D0=B4=20=D0=B3=D0=BE=D1=82?= =?UTF-8?q?=D0=BE=D0=B2...=20=D0=BF=D0=B8=D1=88=D1=83=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/Collection.js | 62 ++++++++++ Task/Model.js | 1 + Task/baseEvent.js | 184 +++++++++++++++--------------- Task/baseEventTest.js | 92 +++++++-------- Task/event.js | 128 ++++++++++----------- Task/test/trivialSqlCommands.html | 3 +- 6 files changed, 265 insertions(+), 205 deletions(-) create mode 100644 Task/Collection.js diff --git a/Task/Collection.js b/Task/Collection.js new file mode 100644 index 0000000..0b74334 --- /dev/null +++ b/Task/Collection.js @@ -0,0 +1,62 @@ +Collection = function (otherItems) { + var item; + this.items = []; + for(item in otherItems) { + if (otherItems.hasOwnProperty(item)) { + this.items.push(otherItems[item]); + } + } +}; + +/** + * @param {Model} + * @help Создает коллекцию со старыми элементами текущей коллекции + новый элемент. + * @return {Collection} + */ +Collection.prototype.add = function (model) { + var newEvents = [model].concat(this.events); + return new Collection(newEvents); +} +/** + * @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) { + var newItems = this.items.filter(selector); + return new Collection(newItems); +} +/** + * @return {Collection} + */ +Collection.prototype.sortBy = function (comparator, isDownToUp) { + var newItems = [].concat(this.events); + if (newItems.length == 0) { + return []; + } + if (comparator) { + if (isDownToUp) { + var tempComparator = function(a, b) { + return -1*comparator(a, b) + } + comparator = tempComparator; + } + newItems.sort(comparator); + } + else { + newItems.sort(); + } + return new Collection(newItems); +} +// Другие необходимые вам поля + + + + + diff --git a/Task/Model.js b/Task/Model.js index 711a467..5903d1e 100644 --- a/Task/Model.js +++ b/Task/Model.js @@ -19,6 +19,7 @@ Model.prototype.set = function (attributes) { } } } + }; /** * @param {String} attribute diff --git a/Task/baseEvent.js b/Task/baseEvent.js index 489a47c..bb745da 100644 --- a/Task/baseEvent.js +++ b/Task/baseEvent.js @@ -1,4 +1,4 @@ -/** +/** * Shell for "sql" operations with Array Events. * * @constructor @@ -16,100 +16,96 @@ */ function BaseEvent(events) { "use strict"; + Collection.call(this,events); this.events = events; - //пропущенные, текущие, будущие события - this.pastEventBase = function () { - var currentDate = new Date(), needs; - needs = this.events.filter(function (event) { - return event.end.getTime() < currentDate.getTime(); - }); - return new BaseEvent(needs); - }; - this.nextEventBase = function () { - var currentDate = new Date(), needs; - needs = this.events.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); - return new BaseEvent(needs); - }; - this.nowEventBase = function () { - var currentDate = new Date(), needs; - needs = this.events.filter(function (event) { - return (event.start.getTime() <= currentDate.getTime() && event.end.getTime() >= currentDate.getTime()); - }); - return new BaseEvent(needs); - }; - //событие с участием друга (Друг отношение рефлексивное ^^) - this.withFriend = function (myFriend) { - var needs = this.events.filter(function (event) { - return event.parties.some(function (party) { - return party.name === myFriend.name; - }); - }); - return new BaseEvent(needs); - }; - // События через период времени день, неделя, месяц - this.getEventAfterWeek = function () { - var currentDate = new Date(), needs; - currentDate = new Date(currentDate.getTime() + 7 * 24 * 60 * 60 * 1000); - needs = this.events.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); - return new BaseEvent(needs); - }; - this.getEventAfterDay = function () { - var currentDate = new Date(), needs; - currentDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000); - needs = this.events.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); - return new BaseEvent(needs); - }; - this.getEventAfterMonth = function () { - var currentDate = new Date(), needs; - if (currentDate.getMonth() === 11) { - currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay()); - } else { - currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDay()); +} +BaseEvent.prototype = Object.create(Collection.prototype, { + constructor: { + value: BaseEvent, + enumerable: false, + writable: true, + configurable: true +}}); + + +//пропущенные, текущие, будущие события +BaseEvent.prototype.pastEventBase = function () { + var currentDate = new Date(); + return this.filter(function (event) { + return event.end.getTime() < currentDate.getTime(); + }); +}; +BaseEvent.prototype.nextEventBase = function () { + var currentDate = new Date(); + return this.filter(function (event) { + return event.start.getTime() > currentDate.getTime(); + }); +}; +BaseEvent.prototype.nowEventBase = function () { + 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) { + return this.filter(function (event) { + return event.parties.some(function (party) { + return party.name === myFriend.name; + })}); +}; +// События через период времени день, неделя, месяц +BaseEvent.prototype.getEventAfterWeek = function () { + 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 () { + 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 () { + 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) { + return this.filter(function (event) { + return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); + }); +}; +BaseEvent.prototype.sortByStars = function (ascending) { + var comparer = function compare(a, b) { + if (a.stars > b.stars) { + return -1; } - needs = this.events.filter(function (event) { - return event.start.getTime() > currentDate.getTime(); - }); - return new BaseEvent(needs); - }; - // События за период - this.getEventFromPeriod = function (fromDate, toDate) { - var needs = this.events.filter(function (event) { - return (event.start.getTime() > fromDate.getTime() && event.end.getTime() < toDate.getTime()); - }); - return new BaseEvent(needs); - }; - this.sortByStars = function () { - var events = this.events.slice(0), comparer; - comparer = function compare(a, b) { - if (a.stars > b.stars) { - return -1; - } - if (a.stars < b.stars) { - return 1; - } - return 0; - }; - events.sort(comparer); - return new BaseEvent(events); + if (a.stars < b.stars) { + return 1; + } + return 0; }; - this.sortByDate = function () { - var events = this.events.slice(0), comparer; - 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; - }; - events.sort(comparer); - return new BaseEvent(events); + return this.sortBy(comparer, ascending); +}; +BaseEvent.prototype.sortByDate = function (ascending) { + 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; }; -} \ No newline at end of file + return this.sortBy(comparer, ascending); +}; + diff --git a/Task/baseEventTest.js b/Task/baseEventTest.js index e3257ce..daf7ebb 100644 --- a/Task/baseEventTest.js +++ b/Task/baseEventTest.js @@ -11,11 +11,11 @@ test('pastEventBase()', function () { return new RealDate("September 13, 2012 12:00:00"); }; pastEventbase = testBase.pastEventBase(); - equal(pastEventbase.events.length, 2); - ok(pastEventbase.events.some(function (event) { + equal(pastEventbase.items.length, 2); + ok(pastEventbase.items.some(function (event) { return event.id === 15; })); - ok(pastEventbase.events.some(function (event) { + ok(pastEventbase.items.some(function (event) { return event.id === 17; })); Date = RealDate; @@ -27,11 +27,11 @@ test('nextEventBase()', function () { return new RealDate("November 1, 2012 12:00:00"); }; nextEventBase = testBase.nextEventBase(); - equal(nextEventBase.events.length, 2); - ok(nextEventBase.events.some(function (event) { + equal(nextEventBase.items.length, 2); + ok(nextEventBase.items.some(function (event) { return event.id === 19; })); - ok(nextEventBase.events.some(function (event) { + ok(nextEventBase.items.some(function (event) { return event.id === 20; })); Date = RealDate; @@ -43,8 +43,8 @@ test('nowEventBase()', function () { return new RealDate("September 13, 2012 12:00:00"); }; nowEventbase = testBase.nowEventBase(); - equal(nowEventbase.events.length, 1); - ok(nowEventbase.events.some(function (event) { + equal(nowEventbase.items.length, 1); + ok(nowEventbase.items.some(function (event) { return event.id === 16; })); Date = RealDate; @@ -52,8 +52,8 @@ test('nowEventBase()', function () { test('withFriend("Alexander.Mangin")', function () { "use strict"; var testBase = initTestBase(), eventWithFriendBase = testBase.withFriend({name: "Alexander.Mangin"}); - equal(eventWithFriendBase.events.length, 1); - ok(eventWithFriendBase.events.some(function (event) { + equal(eventWithFriendBase.items.length, 1); + ok(eventWithFriendBase.items.some(function (event) { return event.id === 16; })); }); @@ -67,11 +67,11 @@ test('getEventAfterMonth()', function () { return new RealDate("October 1, 2012 12:00:00"); }; eventAfterMonthbase = testBase.getEventAfterMonth(); - equal(eventAfterMonthbase.events.length, 2); - ok(eventAfterMonthbase.events.some(function (event) { + equal(eventAfterMonthbase.items.length, 2); + ok(eventAfterMonthbase.items.some(function (event) { return event.id === 19; })); - ok(eventAfterMonthbase.events.some(function (event) { + ok(eventAfterMonthbase.items.some(function (event) { return event.id === 20; })); Date = RealDate; @@ -86,11 +86,11 @@ test('getEventAfterDay()', function () { return new RealDate("November 1, 2012 12:00:00"); }; eventAfterDaybase = testBase.getEventAfterDay(); - equal(eventAfterDaybase.events.length, 2); - ok(eventAfterDaybase.events.some(function (event) { + equal(eventAfterDaybase.items.length, 2); + ok(eventAfterDaybase.items.some(function (event) { return event.id === 19; })); - ok(eventAfterDaybase.events.some(function (event) { + ok(eventAfterDaybase.items.some(function (event) { return event.id === 20; })); Date = RealDate; @@ -105,8 +105,8 @@ test('getEventAfterWeek()', function () { return new RealDate("October 28, 2012 12:00:00"); }; eventAfterWeekbase = testBase.getEventAfterWeek(); - equal(eventAfterWeekbase.events.length, 1); - ok(eventAfterWeekbase.events.some(function (event) { + equal(eventAfterWeekbase.items.length, 1); + ok(eventAfterWeekbase.items.some(function (event) { return event.id === 19; })); Date = RealDate; @@ -115,8 +115,8 @@ test('getEventFromPeriod(from,to)', function () { "use strict"; var testBase = initTestBase(), result; result = testBase.getEventFromPeriod(new Date("September 12 2012 00:00:00"), new Date("September 14 2012 00:00:00")); - equal(result.events.length, 1); - ok(result.events.some(function (event) { + equal(result.items.length, 1); + ok(result.items.some(function (event) { return event.id === 16; })); }); @@ -124,79 +124,79 @@ test('getEventFromPeriod(from,to)', function () { test('sortByStar()', function () { "use strict"; var testBase = initTestBase(), sortByStarsEventbase = testBase.sortByStars(); - equal(testBase.events.length, sortByStarsEventbase.events.length); - ok(sortByStarsEventbase.events[0].stars === 5); - ok(sortByStarsEventbase.events[1].stars === 5); + equal(testBase.items.length, sortByStarsEventbase.items.length); + ok(sortByStarsEventbase.items[0].stars === 5); + ok(sortByStarsEventbase.items[1].stars === 5); }); test('sortByDate()', function () { "use strict"; var testBase = initTestBase(), sortByDateEventbase = testBase.sortByDate(); - equal(testBase.events.length, sortByDateEventbase.events.length); - ok(sortByDateEventbase.events[0].id === 15); - ok(sortByDateEventbase.events[1].id === 17); + equal(testBase.items.length, sortByDateEventbase.items.length); + ok(sortByDateEventbase.items[0].id === 15); + ok(sortByDateEventbase.items[1].id === 17); }); function initTestBase() { "use strict"; var bestOfSweetsDateStart = new Date("October 10, 2012 00:00:00"), bestOfSweetsDateFinish = new Date("October 14, 2012 23:59:59"), - bestOfSweets = new Event(bestOfSweetsDateStart, bestOfSweetsDateFinish, "BestOfSweets", 1), + bestOfSweets = new Event({"start":bestOfSweetsDateStart, "end":bestOfSweetsDateFinish,"name": "BestOfSweets","id": 1}), сirioDeNazareDateStart = new Date("October 8, 2012 00:00:00"), сirioDeNazareDateFinish = new Date("October 15, 2012 23:59:59"), - сirioDeNazare = new Event(сirioDeNazareDateStart, сirioDeNazareDateFinish, "Cirio De Nazare", 2), + сirioDeNazare = new Event({"start":сirioDeNazareDateStart, "end":сirioDeNazareDateFinish, "name":"Cirio De Nazare", "id":2}), vinesDayDateStart = new Date("October 4, 2012 00:00:00"), vinesDayDateFinish = new Date("October 6, 2012 23:59:59"), - vinesDay = new Event(vinesDayDateStart, vinesDayDateFinish, "День вина", 3), + vinesDay = new Event({"start":vinesDayDateStart, "end":vinesDayDateFinish, "name":"День вина", "id":3}), theBlackCountryDateStart = new Date("October 31, 2012 00:00:00"), theBlackCountryDateFinish = new Date("November 1, 2012 23:59:59"), - theBlackCountry = new Event(theBlackCountryDateStart, theBlackCountryDateFinish, 'Вкус "Черной страны"', 4), + theBlackCountry = new Event({"start":theBlackCountryDateStart, "end":theBlackCountryDateFinish, "name":'Вкус "Черной страны"', "id":4}), oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), - oktoberFest = new Event(oktoberFestDateStart, oktoberFestDateFinish, 'OktoberFest', 5), + oktoberFest = new Event({"start":oktoberFestDateStart, "end":oktoberFestDateFinish, "name":'OktoberFest', "id":5}), francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), - francfurtBook = new Event(francfurtBookDateStart, francfurtBookDateFinish, 'Франкфуртская международная книжная ярмарка', 6), + francfurtBook = new Event({"start":francfurtBookDateStart, "end":francfurtBookDateFinish, "name":'Франкфуртская международная книжная ярмарка', "id":6}), aidaDateStart = new Date("October 12, 2012 00:00:00"), aidaDateFinish = new Date("October 27, 2012 23:59:59"), - aida = new Event(aidaDateStart, aidaDateFinish, '"Аида" у великих пирамид, Гиза', 7), + aida = new Event({"start":aidaDateStart, "end":aidaDateFinish, "name":'"Аида" у великих пирамид, Гиза', "id":7}), paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), - paradeOfLove = new Event(aidaDateStart, aidaDateFinish, 'Парад любви', 8), + paradeOfLove = new Event({"start":paradeOfLoveDateStart, "end":paradeOfLoveDateFinish, "name":'Парад любви', "id":8}), sukkotDateStart = new Date("October 3, 2012 00:00:00"), sukkotDateFinish = new Date("October 3, 2012 23:59:59"), - sukkot = new Event(aidaDateStart, aidaDateFinish, 'Парад любви', 9), + sukkot = new Event({"start":sukkotDateStart, "end":sukkotDateFinish, "name":'Парад любви', "id":9}), fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), - fishFestival = new Event(fishFestivalDateStart, fishFestivalDateStart, 'Фестиваль рыбы', 10), + fishFestival = new Event({"start":fishFestivalDateStart, "end":fishFestivalDateFinish, "name":'Фестиваль рыбы', "id":10}), chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), - chocolateFestival = new Event(fishFestivalDateStart, fishFestivalDateStart, 'Фестиваль "Еврошоколад"', 11), + chocolateFestival = new Event({"start":chocolateFestivalDateStart, "end":chocolateFestivalDateFinish, "name":'Фестиваль "Еврошоколад"', "id":11}), digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), - digitalArtFestival = new Event(digitalArtFestivalDateStart, digitalArtFestivalDateFinish, 'Фестиваль цифрового исскуства', 12), + digitalArtFestival = new Event({"start":digitalArtFestivalDateStart, "end":digitalArtFestivalDateFinish, "name":'Фестиваль цифрового исскуства', "id":12}), fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), - fatherDays = new Event(fatherDaysDateStart, fatherDaysDateFinish, 'Дни наследия', 13), + fatherDays = new Event({"start":fatherDaysDateStart, "end":fatherDaysDateFinish, "name":'Дни наследия', "id":13}), bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), - bearWeekend = new Event(bearWeekendDateStart, bearWeekendDateFinish, 'Bear Weekends', 14), + bearWeekend = new Event({"start":bearWeekendDateStart, "end":bearWeekendDateFinish, "name":'Bear Weekends', "id":14}), teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), - teaFestival = new Event(teaFestivalDateStart, teaFestivalDateFinish, 'Фестиваль Чая', 15), + teaFestival = new Event({"start":teaFestivalDateStart, "end":teaFestivalDateFinish, "name":'Фестиваль Чая', "id":15}), programmerDayDateStart = new Date("September 13, 2012 00:00:00"), programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), - programmerDay = new Event(programmerDayDateStart, programmerDayDateFinish, 'День программмиста', 16), + programmerDay = new Event({"start":programmerDayDateStart, "end":programmerDayDateFinish, "name":'День программмиста', "id":16}), knowDayDateStart = new Date("September 1, 2012 00:00:01"), knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), - knowDayDate = new Event(knowDayDateStart, knowDayDateDateFinish, 'День знаний', 17), + knowDayDate = new Event({"start":knowDayDateStart, "end":knowDayDateDateFinish, "name":'День знаний', "id":17}), teacherDayDateStart = new Date("October 5, 2012 00:00:00"), teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), - teacherDay = new Event(teacherDayDateStart, teacherDayDateFinish, 'День учителя', 18), + teacherDay = new Event({"start":teacherDayDateStart, "end":teacherDayDateFinish, "name":'День учителя', "id":18}), securiteDayDateStart = new Date("November 5, 2012 00:00:00"), securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), - securiteDay = new Event(securiteDayDateStart, securiteDayDateFinish, 'День защиты информации', 19), + securiteDay = new Event({"start":securiteDayDateStart, "end":securiteDayDateFinish, "name":'День защиты информации', "id":19}), nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), - nationUnition = new Event(nationUnitionDateStart, nationUnitionDateDateFinish, 'День нароного единства', 20); + nationUnition = new Event({"start":nationUnitionDateStart, "end":nationUnitionDateDateFinish, "name":'День нароного единства', "id":20}); bestOfSweets.setLocation({gps :{x : 15, y : 189, name : "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"}}); bestOfSweets.leaveMark(2); сirioDeNazare.setLocation({gps :{x : 45, y : 133, name : "Бразилия, Белен, Фестиваль Cirio De Nazare"}}); diff --git a/Task/event.js b/Task/event.js index 268f332..25c17fe 100644 --- a/Task/event.js +++ b/Task/event.js @@ -14,76 +14,76 @@ */ function Event(data) { - "use strict"; + "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(); + if (!this.validate(this)) { + throw new Error("Объект не прошел валидацию"); + } + this.setLocation(this.location); + this.leaveMark(this.stars); } +Event.prototype = Object.create(Model.prototype, { + constructor: { + value: Event, + enumerable: false, + writable: true, + configurable: true +}}); -(function () { - var inherits = function (Constructor, SuperConstructor) { - var tempConstructor = function () {}; - tempConstructor.prototype = SuperConstructor.prototype; - Constructor.prototype = new tempConstructor(); - } - - inherits(Event, Model); - - Event.prototype.dateValidator = function (date) { - if (Object.prototype.toString.call(date) === "[object Date]") { - if (!isNaN(date.getTime())) { - return true; - } +Event.prototype.dateValidator = function (date) { + if (Object.prototype.toString.call(date) === "[object Date]") { + if (!isNaN(date.getTime())) { + return true; } - return false; } - Event.prototype.setLocation = function (gps, name) { - 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) { - 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 () { - var tempDate; - this.id = this.id || Math.random(); - this.location = this.location || { - "gps": {x: 0, y: 0}, - "nameLocation": "Earth" - }; - this.location = this.location || []; - this.stars = this.stars || 0; - this.cost = this.cost || 0; - this.parties =this.parties || []; - - if (!this.dateValidator(this.start)) { - this.start = new Date(); - } - if (!this.dateValidator(this.end)) { - this.end = this.start; - } - if (this.end < this.start) { - tempDate = this.start; - this.start = this.end; - this.end = tempDate; - } - this.setLocation(this.location); - this.leaveMark(this.stars); + return false; +} +Event.prototype.setLocation = function (gps, name) { + 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) { + 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) { + 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("Даты начала и конца перепутаны"); + } + return true } -}()); diff --git a/Task/test/trivialSqlCommands.html b/Task/test/trivialSqlCommands.html index bc091ae..966edd3 100644 --- a/Task/test/trivialSqlCommands.html +++ b/Task/test/trivialSqlCommands.html @@ -4,8 +4,9 @@ - + + From ea754b65a01915f2ea2ce6cdc8072e6863f8bd1f Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Wed, 31 Oct 2012 01:22:15 +0600 Subject: [PATCH 11/16] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B5=D1=89=D0=B5=20=D1=82=D0=B5=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=BD=D0=B0=20Event?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Так же освоил тесты на throws --- Task/CreateEventTest.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/Task/CreateEventTest.js b/Task/CreateEventTest.js index 4ae6196..410f3fd 100644 --- a/Task/CreateEventTest.js +++ b/Task/CreateEventTest.js @@ -5,8 +5,27 @@ return month + "/" + day + "/" + year; }, currentTime = new Date(), testEvent = new Event({"start":currentTime}); equal(dateToString(testEvent.start), dateToString(currentTime)); - testEvent = new Event({"start": new Date(2), "end": new Date(1)}); - ok(testEvent.start.getTime() < testEvent.end.getTime()); testEvent = new Event({"start": new Date(1), "end": new Date(2)}); ok(testEvent.start.getTime() < testEvent.end.getTime()); + + throws( + function (){new Event({"start": new Date(2), "end": new Date(1)})}, + 'Error("Даты начала и конца перепутаны")' + ); + throws( + function (){new Event({"cost":-1})}, + 'Error("Цена за вход не может быть отрицательной")' + ); + throws( + function (){new Event({"parties":"NoArray"})}, + 'Error("Участники - это массив")' + ); + throws( + function (){new Event({"parties":["sds"]})}, + 'Error("У одного из участников нет поля <ИМЯ>")' + ); + equal(new Event({"stars":2}).stars, 2,"При присваивании звезд произошла ошибка" ); + equal(new Event({"stars":2.1}).stars, 2,"Функция устанавливающая звездочки не сработала" ); + + }); \ No newline at end of file From 76e28014873aba4204a880bc0532d3f14c0962d7 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 1 Nov 2012 18:35:40 +0600 Subject: [PATCH 12/16] =?UTF-8?q?=D0=92=D1=81=D0=B5=20=D1=81=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BD=D0=BE=20=D0=B8=20=D0=BF=D1=80=D0=BE=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/{baseEvent.js => BaseEvent.js} | 0 Task/EventLeaveMarkTest.js | 17 ------------- Task/EventSetLocationTest.js | 25 ------------------- ...ialSqlCommands.html => BaseEventTest.html} | 0 .../BaseEventTest.js} | 0 .../{CreateEvent.html => CollectionTest.html} | 0 Task/test/{LeaveMark.html => EventTest.html} | 3 +-- .../{CreateEventTest.js => test/EventTest.js} | 0 ...reateAbstractModet.html => ModelTest.html} | 0 Task/{ => test}/ModelTest.js | 0 Task/test/SetLocation.html | 18 ------------- 11 files changed, 1 insertion(+), 62 deletions(-) rename Task/{baseEvent.js => BaseEvent.js} (100%) delete mode 100644 Task/EventLeaveMarkTest.js delete mode 100644 Task/EventSetLocationTest.js rename Task/test/{trivialSqlCommands.html => BaseEventTest.html} (100%) rename Task/{baseEventTest.js => test/BaseEventTest.js} (100%) rename Task/test/{CreateEvent.html => CollectionTest.html} (100%) rename Task/test/{LeaveMark.html => EventTest.html} (88%) rename Task/{CreateEventTest.js => test/EventTest.js} (100%) rename Task/test/{CreateAbstractModet.html => ModelTest.html} (100%) rename Task/{ => test}/ModelTest.js (100%) delete mode 100644 Task/test/SetLocation.html diff --git a/Task/baseEvent.js b/Task/BaseEvent.js similarity index 100% rename from Task/baseEvent.js rename to Task/BaseEvent.js diff --git a/Task/EventLeaveMarkTest.js b/Task/EventLeaveMarkTest.js deleted file mode 100644 index 65908dc..0000000 --- a/Task/EventLeaveMarkTest.js +++ /dev/null @@ -1,17 +0,0 @@ -test('Leave Mark', function () { - "use strict"; - var testEvent = new Event({}); - testEvent.leaveMark("No number"); - equal(testEvent.stars, 0, 'Если звездочку передали в виде не числа, то 0'); - var undefinedVar; - testEvent.leaveMark(undefinedVar); - equal(testEvent.stars, 0, 'Если звездочку забыли объявить, то 0'); - testEvent.leaveMark(-1); - equal(testEvent.stars, 0, 'Звездочка не может быть меньше 0'); - testEvent.leaveMark(6); - equal(testEvent.stars, 5, 'Звездочка не может быть больше 5'); - testEvent.leaveMark(3); - equal(testEvent.stars, 3, '0-5 звездочка не изменяется, если целая'); - testEvent.leaveMark(3.124); - equal(testEvent.stars, 3, 'Звездочки - Int'); -}); \ No newline at end of file diff --git a/Task/EventSetLocationTest.js b/Task/EventSetLocationTest.js deleted file mode 100644 index 16844e8..0000000 --- a/Task/EventSetLocationTest.js +++ /dev/null @@ -1,25 +0,0 @@ -test('Set location',function () { - "use strict"; - var testEvent = new Event({}),gps; - testEvent.setLocation(gps,""); - deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "GPS - некорректный => установить значения по умолчанию"); - testEvent.setLocation("Not gps",""); - deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "GPS - не содержит X или Y => установить значения по умолчанию"); - testEvent.setLocation({"x": 0,"y": 0},[]); - deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "Название места не строка => установить значения по умолчанию"); - testEvent.setLocation({"x": 1,"y": 2},"Moon"); - deepEqual(testEvent.location, { - "gps" : {"x": 1,"y": 2}, - "nameLocation" : "Moon" - }, "GPS - не содержит X или Y => установить значения по умолчанию"); - -}); \ No newline at end of file diff --git a/Task/test/trivialSqlCommands.html b/Task/test/BaseEventTest.html similarity index 100% rename from Task/test/trivialSqlCommands.html rename to Task/test/BaseEventTest.html diff --git a/Task/baseEventTest.js b/Task/test/BaseEventTest.js similarity index 100% rename from Task/baseEventTest.js rename to Task/test/BaseEventTest.js diff --git a/Task/test/CreateEvent.html b/Task/test/CollectionTest.html similarity index 100% rename from Task/test/CreateEvent.html rename to Task/test/CollectionTest.html diff --git a/Task/test/LeaveMark.html b/Task/test/EventTest.html similarity index 88% rename from Task/test/LeaveMark.html rename to Task/test/EventTest.html index da075a3..9235784 100644 --- a/Task/test/LeaveMark.html +++ b/Task/test/EventTest.html @@ -6,8 +6,7 @@ - - + diff --git a/Task/CreateEventTest.js b/Task/test/EventTest.js similarity index 100% rename from Task/CreateEventTest.js rename to Task/test/EventTest.js diff --git a/Task/test/CreateAbstractModet.html b/Task/test/ModelTest.html similarity index 100% rename from Task/test/CreateAbstractModet.html rename to Task/test/ModelTest.html diff --git a/Task/ModelTest.js b/Task/test/ModelTest.js similarity index 100% rename from Task/ModelTest.js rename to Task/test/ModelTest.js diff --git a/Task/test/SetLocation.html b/Task/test/SetLocation.html deleted file mode 100644 index 2404f50..0000000 --- a/Task/test/SetLocation.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - -

            QUnit test env

            -

            -

            -
              - - \ No newline at end of file From 51571d82e8cc677d8021d42d69ebf5cb2dcd1cd1 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 1 Nov 2012 18:36:25 +0600 Subject: [PATCH 13/16] =?UTF-8?q?=D0=92=D1=81=D0=B5=20=D1=81=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BD=D0=BE=20=D0=B8=20=D0=BF=D1=80=D0=BE=D1=82?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Дописал QUnit тесты 2. Перекодировал файлы.. которые забыл перекодировать 3. Рефакторниг. ...... Осталось JSLint and JSDoc --- Task/Collection.js | 20 ++++---- Task/Model.js | 2 +- Task/event.js | 5 +- Task/test/BaseEventTest.html | 4 +- Task/test/BaseEventTest.js | 2 +- Task/test/CollectionTest.html | 7 +-- Task/test/CollectionTest.js | 72 ++++++++++++++++++++++++++++ Task/test/EventTest.html | 4 +- Task/test/EventTest.js | 90 ++++++++++++++++++++++++++++++++++- Task/test/ModelTest.html | 4 +- Task/test/ModelTest.js | 4 +- 11 files changed, 180 insertions(+), 34 deletions(-) create mode 100644 Task/test/CollectionTest.js diff --git a/Task/Collection.js b/Task/Collection.js index 0b74334..a1f6a81 100644 --- a/Task/Collection.js +++ b/Task/Collection.js @@ -9,12 +9,12 @@ Collection = function (otherItems) { }; /** - * @param {Model} + * @param {obj} * @help Создает коллекцию со старыми элементами текущей коллекции + новый элемент. * @return {Collection} */ -Collection.prototype.add = function (model) { - var newEvents = [model].concat(this.events); +Collection.prototype.add = function (obj) { + var newEvents = this.items.concat([obj]); return new Collection(newEvents); } /** @@ -35,19 +35,19 @@ Collection.prototype.filter = function (selector) { /** * @return {Collection} */ -Collection.prototype.sortBy = function (comparator, isDownToUp) { - var newItems = [].concat(this.events); +Collection.prototype.sortBy = function (comparator, isInvert) { + var newItems = [].concat(this.items); if (newItems.length == 0) { return []; } if (comparator) { - if (isDownToUp) { - var tempComparator = function(a, b) { + if (isInvert) { + newItems.sort(function(a, b) { return -1*comparator(a, b) - } - comparator = tempComparator; + }); + } else { + newItems.sort(comparator); } - newItems.sort(comparator); } else { newItems.sort(); diff --git a/Task/Model.js b/Task/Model.js index 5903d1e..de453a8 100644 --- a/Task/Model.js +++ b/Task/Model.js @@ -1,4 +1,4 @@ -var Model = function (data) { +var Model = function (data) { var nameField; for(nameField in data) { this[nameField] = data[nameField]; diff --git a/Task/event.js b/Task/event.js index 25c17fe..7ea08b9 100644 --- a/Task/event.js +++ b/Task/event.js @@ -24,9 +24,7 @@ function Event(data) { this.cost = 0; this.parties = []; Model.call(this,data); - if (!this.validate(this)) { - throw new Error("Объект не прошел валидацию"); - } + this.validate(this); this.setLocation(this.location); this.leaveMark(this.stars); } @@ -83,7 +81,6 @@ Event.prototype.validate = function (event) { if (event.end < event.start) { throw new Error("Даты начала и конца перепутаны"); } - return true } diff --git a/Task/test/BaseEventTest.html b/Task/test/BaseEventTest.html index 966edd3..55ff875 100644 --- a/Task/test/BaseEventTest.html +++ b/Task/test/BaseEventTest.html @@ -1,4 +1,3 @@ - @@ -8,8 +7,7 @@ - - +

              QUnit test env

              diff --git a/Task/test/BaseEventTest.js b/Task/test/BaseEventTest.js index daf7ebb..1dacd4b 100644 --- a/Task/test/BaseEventTest.js +++ b/Task/test/BaseEventTest.js @@ -1,4 +1,4 @@ -/*global module: true*/ +/*global module: true*/ /*global test: true*/ /*global ok: true*/ /*global equal: true*/ diff --git a/Task/test/CollectionTest.html b/Task/test/CollectionTest.html index 9235784..3b731a5 100644 --- a/Task/test/CollectionTest.html +++ b/Task/test/CollectionTest.html @@ -1,13 +1,10 @@ - - - - - + +

              QUnit test env

              diff --git a/Task/test/CollectionTest.js b/Task/test/CollectionTest.js new file mode 100644 index 0000000..3fb7be6 --- /dev/null +++ b/Task/test/CollectionTest.js @@ -0,0 +1,72 @@ +module("Конструктор"); +test("Конструктор", function() { + "use strict"; + var newCollection = new Collection([1,2,3,4]); + deepEqual(newCollection.items,[1,2,3,4]); +}); +module("Add(model)"); +test("Добавление элемента в пустую коллекцию", function() { + "use strict"; + var newCollection = new Collection(); + newCollection = newCollection.add(1); + deepEqual(newCollection.items,[1]); +}) +test("Добавление элемента в не пустую коллекцию", function() { + "use strict"; + var newCollection = new Collection([2]); + newCollection = newCollection.add(1); + deepEqual(newCollection.items,[2, 1]); +}) +module("filter(function)"); +test("Пример использование filter", function() { + "use strict"; + var newCollection = new Collection([1,2,3,4,5,6]); + newCollection = newCollection.filter(function(element){return (element % 2 === 0)}); + + deepEqual(newCollection.items,[2, 4, 6]); +}) +module("sortBy(function)"); +test("С использование своего компаратора, без инвертирования результата", function() { + "use strict"; + var newCollection = new Collection([{"id" : 8}, {"id" : 2}, {"id" : 3}, + {"id" : 4}, {"id" : 14}, {"id" : 9}]); + var comparator = function (a, b) { + if (a.id > b.id) { + return 1; + } + if (a.id < b.id) { + return -1; + } + return 0; + }; + newCollection = newCollection.sortBy(comparator); + + deepEqual(newCollection.items,[{"id" : 2}, {"id" : 3}, {"id" : 4}, + {"id" : 8}, {"id" : 9}, {"id" : 14}]); +}) +test("С использование своего компаратора, c инвертированием результата", function() { + "use strict"; + var newCollection = new Collection([{"id" : 8}, {"id" : 2}, {"id" : 3}, + {"id" : 4}, {"id" : 14}, {"id" : 9}]); + var comparator = function (a, b) { + if (a.id > b.id) { + return 1; + } + if (a.id < b.id) { + return -1; + } + return 0; + }; + newCollection = newCollection.sortBy(comparator, true); + + deepEqual(newCollection.items,[{"id" : 14}, {"id" : 9}, {"id" : 8}, + {"id" : 4}, {"id" : 3}, {"id" : 2}]); +}) + +test("Сортировка по default", function() { + "use strict"; + var newCollection = new Collection([3, 2, 1]); + newCollection = newCollection.sortBy(); + + deepEqual(newCollection.items,[1, 2, 3]); +}) \ No newline at end of file diff --git a/Task/test/EventTest.html b/Task/test/EventTest.html index 9235784..ddfd84d 100644 --- a/Task/test/EventTest.html +++ b/Task/test/EventTest.html @@ -1,4 +1,3 @@ - @@ -6,8 +5,7 @@ - - +

              QUnit test env

              diff --git a/Task/test/EventTest.js b/Task/test/EventTest.js index 410f3fd..1111192 100644 --- a/Task/test/EventTest.js +++ b/Task/test/EventTest.js @@ -1,4 +1,5 @@ -test('Create event', function () { +module("Tests of Event's constructor"); +test('Create event', function () { "use strict"; var dateToString = function (currentTime) { var month = currentTime.getMonth() + 1, day = currentTime.getDate(), year = currentTime.getFullYear(); @@ -28,4 +29,89 @@ equal(new Event({"stars":2.1}).stars, 2,"Функция устанавливающая звездочки не сработала" ); -}); \ No newline at end of file +}); + +module("LeaveMark(number)"); +test('Передача не числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark("No number"); + equal(testEvent.stars, 0, 'Если звездочку передали в виде не числа, то 0'); +}); +test('Запуск без параметра', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(); + equal(testEvent.stars, 0, 'Если звездочку забыли объявить, то 0'); +}); +test('Передача отрицательного числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(-1); + equal(testEvent.stars, 0, 'Звездочка не может быть меньше 0'); +}); +test('Передача числа болешьшего 5', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(6); + equal(testEvent.stars, 5, 'Звездочка не может быть больше 5'); +}); +test('Передача корректного числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(3); + equal(testEvent.stars, 3, '0-5 звездочка не изменяется, если целая'); +}); +test('Передача дробного числа', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.leaveMark(3.124); + equal(testEvent.stars, 3, 'Звездочки - Int'); +}); + +module("SetLocation(location)"); +test('Gps - undef', function () { + "use strict"; + var testEvent = new Event({}),gps; + testEvent.setLocation(gps,""); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); +}); +test('Передача числа болешьшего 5', function () { + "use strict"; + var testEvent = new Event({}),gps; + testEvent.setLocation(gps,""); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); +}); +test('Передача объекта не являющимся gps', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.setLocation("Not gps",""); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); +}); +test('Имя места - не строка', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.setLocation({"x": 0,"y": 0},[]); + deepEqual(testEvent.location, { + "gps" : {"x": 0,"y": 0}, + "nameLocation" : "Earth" + }, "Название места не строка => установить значения по умолчанию"); +}); +test('Корректный тест', function () { + "use strict"; + var testEvent = new Event({}); + testEvent.setLocation({"x": 1,"y": 2},"Moon"); + deepEqual(testEvent.location, { + "gps" : {"x": 1,"y": 2}, + "nameLocation" : "Moon" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); +}); diff --git a/Task/test/ModelTest.html b/Task/test/ModelTest.html index 78ae495..0524484 100644 --- a/Task/test/ModelTest.html +++ b/Task/test/ModelTest.html @@ -1,12 +1,10 @@ - - - +

              QUnit test env

              diff --git a/Task/test/ModelTest.js b/Task/test/ModelTest.js index 2428410..4f3e0d0 100644 --- a/Task/test/ModelTest.js +++ b/Task/test/ModelTest.js @@ -1,4 +1,4 @@ -module("Create model") +module("Create model") test('Проверка конструктора клонирования', function () { "use strict"; var model = new Model(new TestObject(1)); @@ -26,7 +26,7 @@ test('Проверка метода set()', function () { function TestObject (number) { this.myNumber = number; - }; + } TestObject.prototype.commonNumber = 20; From bcdb3695131d7bca9ffc644dc4dd208a4bff3c99 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 1 Nov 2012 18:42:30 +0600 Subject: [PATCH 14/16] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=BA=D0=BB=D1=8F?= =?UTF-8?q?=D1=82=D0=B0=D1=8F=20=D0=BA=D0=BE=D0=B4=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Оказывается UTF8 Без BOM плохо отображается в браузере. А NetBeans - видит символ BOM как отдельный символ --- Task/BaseEvent.js | 2 +- Task/Collection.js | 2 +- Task/event.js | 2 +- Task/test/BaseEventTest.html | 2 +- Task/test/BaseEventTest.js | 2 +- Task/test/CollectionTest.html | 2 +- Task/test/CollectionTest.js | 2 +- Task/test/EventTest.html | 2 +- Task/test/EventTest.js | 2 +- Task/test/ModelTest.html | 2 +- Task/test/ModelTest.js | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Task/BaseEvent.js b/Task/BaseEvent.js index bb745da..46a43bb 100644 --- a/Task/BaseEvent.js +++ b/Task/BaseEvent.js @@ -1,4 +1,4 @@ -/** +/** * Shell for "sql" operations with Array Events. * * @constructor diff --git a/Task/Collection.js b/Task/Collection.js index a1f6a81..3afb369 100644 --- a/Task/Collection.js +++ b/Task/Collection.js @@ -1,4 +1,4 @@ -Collection = function (otherItems) { +Collection = function (otherItems) { var item; this.items = []; for(item in otherItems) { diff --git a/Task/event.js b/Task/event.js index 7ea08b9..e781005 100644 --- a/Task/event.js +++ b/Task/event.js @@ -1,4 +1,4 @@ -/** +/** * Creates an instance of Event. * * @param {data} - is start event diff --git a/Task/test/BaseEventTest.html b/Task/test/BaseEventTest.html index 55ff875..e4de052 100644 --- a/Task/test/BaseEventTest.html +++ b/Task/test/BaseEventTest.html @@ -1,4 +1,4 @@ - + diff --git a/Task/test/BaseEventTest.js b/Task/test/BaseEventTest.js index 1dacd4b..daf7ebb 100644 --- a/Task/test/BaseEventTest.js +++ b/Task/test/BaseEventTest.js @@ -1,4 +1,4 @@ -/*global module: true*/ +/*global module: true*/ /*global test: true*/ /*global ok: true*/ /*global equal: true*/ diff --git a/Task/test/CollectionTest.html b/Task/test/CollectionTest.html index 3b731a5..fdbff42 100644 --- a/Task/test/CollectionTest.html +++ b/Task/test/CollectionTest.html @@ -1,4 +1,4 @@ - + diff --git a/Task/test/CollectionTest.js b/Task/test/CollectionTest.js index 3fb7be6..7826181 100644 --- a/Task/test/CollectionTest.js +++ b/Task/test/CollectionTest.js @@ -1,4 +1,4 @@ -module("Конструктор"); +module("Конструктор"); test("Конструктор", function() { "use strict"; var newCollection = new Collection([1,2,3,4]); diff --git a/Task/test/EventTest.html b/Task/test/EventTest.html index ddfd84d..72eff13 100644 --- a/Task/test/EventTest.html +++ b/Task/test/EventTest.html @@ -1,4 +1,4 @@ - + diff --git a/Task/test/EventTest.js b/Task/test/EventTest.js index 1111192..619ba53 100644 --- a/Task/test/EventTest.js +++ b/Task/test/EventTest.js @@ -1,4 +1,4 @@ -module("Tests of Event's constructor"); +module("Tests of Event's constructor"); test('Create event', function () { "use strict"; var dateToString = function (currentTime) { diff --git a/Task/test/ModelTest.html b/Task/test/ModelTest.html index 0524484..f28a42d 100644 --- a/Task/test/ModelTest.html +++ b/Task/test/ModelTest.html @@ -1,4 +1,4 @@ - + diff --git a/Task/test/ModelTest.js b/Task/test/ModelTest.js index 4f3e0d0..456d1ee 100644 --- a/Task/test/ModelTest.js +++ b/Task/test/ModelTest.js @@ -1,4 +1,4 @@ -module("Create model") +module("Create model") test('Проверка конструктора клонирования', function () { "use strict"; var model = new Model(new TestObject(1)); From 67c277292ece2511c6cae3af7173ea170af39b86 Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 1 Nov 2012 20:39:58 +0600 Subject: [PATCH 15/16] =?UTF-8?q?jsLint=20=20=D0=B2=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BD=D1=86=D0=B8=D0=BF=D0=B5=20=D1=83=D0=B4=D0=BE=D0=B2=D0=BE?= =?UTF-8?q?=D0=BB=D0=B5=D1=82=D0=B2=D0=BE=D1=80=D0=B5=D0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Task/BaseEvent.js | 39 +++++--- Task/Collection.js | 39 ++++---- Task/Model.js | 17 ++-- Task/event.js | 42 ++++---- Task/test/BaseEventTest.js | 188 ++++++++++++++++++++---------------- Task/test/CollectionTest.js | 140 ++++++++++++++------------- Task/test/EventTest.js | 94 ++++++++++-------- Task/test/ModelTest.js | 31 ++++-- 8 files changed, 326 insertions(+), 264 deletions(-) diff --git a/Task/BaseEvent.js b/Task/BaseEvent.js index 46a43bb..1780c98 100644 --- a/Task/BaseEvent.js +++ b/Task/BaseEvent.js @@ -1,4 +1,6 @@ -/** +/*global Collection: true*/ + +/** * Shell for "sql" operations with Array Events. * * @constructor @@ -16,59 +18,66 @@ */ function BaseEvent(events) { "use strict"; - Collection.call(this,events); + Collection.call(this, events); this.events = events; } BaseEvent.prototype = Object.create(Collection.prototype, { constructor: { - value: BaseEvent, - enumerable: false, - writable: true, - configurable: true -}}); - - + 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 () { - var currentDate = new Date() + "use strict"; + var currentDate = new Date(); if (currentDate.getMonth() === 11) { currentDate = new Date(currentDate.getFullYear() + 1, 0, currentDate.getDay()); } else { @@ -80,11 +89,13 @@ BaseEvent.prototype.getEventAfterMonth = function () { }; // События за период 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; @@ -97,6 +108,7 @@ BaseEvent.prototype.sortByStars = function (ascending) { 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; @@ -107,5 +119,4 @@ BaseEvent.prototype.sortByDate = function (ascending) { return 0; }; return this.sortBy(comparer, ascending); -}; - +}; \ No newline at end of file diff --git a/Task/Collection.js b/Task/Collection.js index 3afb369..4fc0a34 100644 --- a/Task/Collection.js +++ b/Task/Collection.js @@ -1,7 +1,9 @@ -Collection = function (otherItems) { +/*global Collection: true*/ +Collection = function (otherItems) { + "use strict"; var item; this.items = []; - for(item in otherItems) { + for (item in otherItems) { if (otherItems.hasOwnProperty(item)) { this.items.push(otherItems[item]); } @@ -13,10 +15,11 @@ * @help Создает коллекцию со старыми элементами текущей коллекции + новый элемент. * @return {Collection} */ -Collection.prototype.add = function (obj) { +Collection.prototype.add = function (obj) { + "use strict"; var newEvents = this.items.concat([obj]); return new Collection(newEvents); -} +}; /** * @param {Function} selector * @@ -28,35 +31,31 @@ Collection.prototype.add = function (obj) { * }); * @return {Collection} */ -Collection.prototype.filter = function (selector) { +Collection.prototype.filter = function (selector) { + "use strict"; var newItems = this.items.filter(selector); return new Collection(newItems); -} +}; /** * @return {Collection} */ -Collection.prototype.sortBy = function (comparator, isInvert) { +Collection.prototype.sortBy = function (comparator, isInvert) { + "use strict"; var newItems = [].concat(this.items); - if (newItems.length == 0) { + if (newItems.length === 0) { return []; } if (comparator) { if (isInvert) { - newItems.sort(function(a, b) { - return -1*comparator(a, b) - }); + newItems.sort(function (a, b) { + return -1 * comparator(a, b); + }); } else { newItems.sort(comparator); } - } - else { + } else { newItems.sort(); } return new Collection(newItems); -} -// Другие необходимые вам поля - - - - - +}; +// Другие необходимые вам поля \ No newline at end of file diff --git a/Task/Model.js b/Task/Model.js index de453a8..2aab8b5 100644 --- a/Task/Model.js +++ b/Task/Model.js @@ -1,7 +1,8 @@ var Model = function (data) { + "use strict"; var nameField; - for(nameField in data) { - this[nameField] = data[nameField]; + for (nameField in data) { + this[nameField] = data[nameField]; } }; /** @@ -11,20 +12,21 @@ * item.set({title: "March 20", content: "In his eyes she eclipses..."}); */ Model.prototype.set = function (attributes) { + "use strict"; var nameAttr; - for(nameAttr in attributes) { - if(attributes.hasOwnProperty(nameAttr)) { + for (nameAttr in attributes) { + if (attributes.hasOwnProperty(nameAttr)) { if (typeof this[nameAttr] !== "undefined") { this[nameAttr] = attributes[nameAttr]; } } } - }; /** * @param {String} attribute */ Model.prototype.get = function (attribute) { + "use strict"; if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { return; //return undefined; } @@ -33,4 +35,7 @@ Model.prototype.get = function (attribute) { /** * @param {Object} attributes */ -Model.prototype.validate = function (attributes) {throw new Error('this is Abstract method')}; \ No newline at end of file +Model.prototype.validate = function (attributes) { + "use strict"; + throw new Error('this is Abstract method'); +}; \ No newline at end of file diff --git a/Task/event.js b/Task/event.js index e781005..d554cc5 100644 --- a/Task/event.js +++ b/Task/event.js @@ -1,4 +1,5 @@ -/** +/*global Model: true*/ +/** * Creates an instance of Event. * * @param {data} - is start event @@ -12,51 +13,52 @@ * @method {setLocation} - is setter for location's field * @method {leaveMark} - is setter for stars's field (0,1,2,3,4,5 - допустимые значения) */ - function Event(data) { - "use strict"; + "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); + 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 -}}); - + 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}, + "gps" : {"x" : 0, "y" : 0}, "nameLocation" : "Earth" }; } }; Event.prototype.leaveMark = function (stars) { + "use strict"; if (isNaN(parseFloat(stars)) || !isFinite(stars) || stars < 0) { stars = 0; } @@ -67,20 +69,20 @@ Event.prototype.leaveMark = function (stars) { 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; - })) { + if (event.parties.some(function (party) { + return !party.name; + }) + ) { throw new Error("У одного из участников нет поля <ИМЯ>"); } if (event.end < event.start) { throw new Error("Даты начала и конца перепутаны"); } -} - - +}; \ No newline at end of file diff --git a/Task/test/BaseEventTest.js b/Task/test/BaseEventTest.js index daf7ebb..8554015 100644 --- a/Task/test/BaseEventTest.js +++ b/Task/test/BaseEventTest.js @@ -3,6 +3,7 @@ /*global ok: true*/ /*global equal: true*/ /*global initTestBase: true*/ +/*global Event: true*/ module("test simple SQL"); test('pastEventBase()', function () { "use strict"; @@ -120,7 +121,6 @@ test('getEventFromPeriod(from,to)', function () { return event.id === 16; })); }); - test('sortByStar()', function () { "use strict"; var testBase = initTestBase(), sortByStarsEventbase = testBase.sortByStars(); @@ -137,103 +137,123 @@ test('sortByDate()', function () { }); function initTestBase() { "use strict"; - var bestOfSweetsDateStart = new Date("October 10, 2012 00:00:00"), - bestOfSweetsDateFinish = new Date("October 14, 2012 23:59:59"), - bestOfSweets = new Event({"start":bestOfSweetsDateStart, "end":bestOfSweetsDateFinish,"name": "BestOfSweets","id": 1}), - сirioDeNazareDateStart = new Date("October 8, 2012 00:00:00"), - сirioDeNazareDateFinish = new Date("October 15, 2012 23:59:59"), - сirioDeNazare = new Event({"start":сirioDeNazareDateStart, "end":сirioDeNazareDateFinish, "name":"Cirio De Nazare", "id":2}), - vinesDayDateStart = new Date("October 4, 2012 00:00:00"), - vinesDayDateFinish = new Date("October 6, 2012 23:59:59"), - vinesDay = new Event({"start":vinesDayDateStart, "end":vinesDayDateFinish, "name":"День вина", "id":3}), - theBlackCountryDateStart = new Date("October 31, 2012 00:00:00"), - theBlackCountryDateFinish = new Date("November 1, 2012 23:59:59"), - theBlackCountry = new Event({"start":theBlackCountryDateStart, "end":theBlackCountryDateFinish, "name":'Вкус "Черной страны"', "id":4}), - oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), - oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), - oktoberFest = new Event({"start":oktoberFestDateStart, "end":oktoberFestDateFinish, "name":'OktoberFest', "id":5}), - francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), - francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), - francfurtBook = new Event({"start":francfurtBookDateStart, "end":francfurtBookDateFinish, "name":'Франкфуртская международная книжная ярмарка', "id":6}), - aidaDateStart = new Date("October 12, 2012 00:00:00"), - aidaDateFinish = new Date("October 27, 2012 23:59:59"), - aida = new Event({"start":aidaDateStart, "end":aidaDateFinish, "name":'"Аида" у великих пирамид, Гиза', "id":7}), - paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), - paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), - paradeOfLove = new Event({"start":paradeOfLoveDateStart, "end":paradeOfLoveDateFinish, "name":'Парад любви', "id":8}), - sukkotDateStart = new Date("October 3, 2012 00:00:00"), - sukkotDateFinish = new Date("October 3, 2012 23:59:59"), - sukkot = new Event({"start":sukkotDateStart, "end":sukkotDateFinish, "name":'Парад любви', "id":9}), - fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), - fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), - fishFestival = new Event({"start":fishFestivalDateStart, "end":fishFestivalDateFinish, "name":'Фестиваль рыбы', "id":10}), - chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), - chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), - chocolateFestival = new Event({"start":chocolateFestivalDateStart, "end":chocolateFestivalDateFinish, "name":'Фестиваль "Еврошоколад"', "id":11}), - digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), - digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), - digitalArtFestival = new Event({"start":digitalArtFestivalDateStart, "end":digitalArtFestivalDateFinish, "name":'Фестиваль цифрового исскуства', "id":12}), - fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), - fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), - fatherDays = new Event({"start":fatherDaysDateStart, "end":fatherDaysDateFinish, "name":'Дни наследия', "id":13}), - bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), - bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), - bearWeekend = new Event({"start":bearWeekendDateStart, "end":bearWeekendDateFinish, "name":'Bear Weekends', "id":14}), - teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), - teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), - teaFestival = new Event({"start":teaFestivalDateStart, "end":teaFestivalDateFinish, "name":'Фестиваль Чая', "id":15}), - programmerDayDateStart = new Date("September 13, 2012 00:00:00"), - programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), - programmerDay = new Event({"start":programmerDayDateStart, "end":programmerDayDateFinish, "name":'День программмиста', "id":16}), - knowDayDateStart = new Date("September 1, 2012 00:00:01"), - knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), - knowDayDate = new Event({"start":knowDayDateStart, "end":knowDayDateDateFinish, "name":'День знаний', "id":17}), - teacherDayDateStart = new Date("October 5, 2012 00:00:00"), - teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), - teacherDay = new Event({"start":teacherDayDateStart, "end":teacherDayDateFinish, "name":'День учителя', "id":18}), - securiteDayDateStart = new Date("November 5, 2012 00:00:00"), - securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), - securiteDay = new Event({"start":securiteDayDateStart, "end":securiteDayDateFinish, "name":'День защиты информации', "id":19}), - nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), - nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), - nationUnition = new Event({"start":nationUnitionDateStart, "end":nationUnitionDateDateFinish, "name":'День нароного единства', "id":20}); - bestOfSweets.setLocation({gps :{x : 15, y : 189, name : "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"}}); + var bestOfSweetsDateStart = new Date("October 10, 2012 00:00:00"), + bestOfSweetsDateFinish = new Date("October 14, 2012 23:59:59"), + bestOfSweets = new Event({"start": bestOfSweetsDateStart, "end": bestOfSweetsDateFinish, "name": "BestOfSweets", "id": 1}), + сirioDeNazareDateStart = new Date("October 8, 2012 00:00:00"), + сirioDeNazareDateFinish = new Date("October 15, 2012 23:59:59"), + сirioDeNazare = new Event({"start": сirioDeNazareDateStart, "end": сirioDeNazareDateFinish, "name": "Cirio De Nazare", "id": 2}), + vinesDayDateStart = new Date("October 4, 2012 00:00:00"), + vinesDayDateFinish = new Date("October 6, 2012 23:59:59"), + vinesDay = new Event({"start": vinesDayDateStart, "end": vinesDayDateFinish, "name": "День вина", "id": 3}), + theBlackCountryDateStart = new Date("October 31, 2012 00:00:00"), + theBlackCountryDateFinish = new Date("November 1, 2012 23:59:59"), + theBlackCountry = new Event({"start": theBlackCountryDateStart, "end": theBlackCountryDateFinish, "name": 'Вкус "Черной страны"', "id": 4}), + oktoberFestDateStart = new Date("September 24, 2012 00:00:00"), + oktoberFestDateFinish = new Date("October 8, 2012 23:59:59"), + oktoberFest = new Event({"start": oktoberFestDateStart, "end": oktoberFestDateFinish, "name": 'OktoberFest', "id": 5}), + francfurtBookDateStart = new Date("October 15, 2012 00:00:00"), + francfurtBookDateFinish = new Date("October 20, 2012 23:59:59"), + francfurtBook = new Event({"start": francfurtBookDateStart, "end": francfurtBookDateFinish, "name": 'Франкфуртская международная книжная ярмарка', "id": 6}), + aidaDateStart = new Date("October 12, 2012 00:00:00"), + aidaDateFinish = new Date("October 27, 2012 23:59:59"), + aida = new Event({"start": aidaDateStart, "end": aidaDateFinish, "name": '"Аида" у великих пирамид, Гиза', "id": 7}), + paradeOfLoveDateStart = new Date("October 3, 2012 14:00:00"), + paradeOfLoveDateFinish = new Date("October 3, 2012 22:00:00"), + paradeOfLove = new Event({"start": paradeOfLoveDateStart, "end": paradeOfLoveDateFinish, "name": 'Парад любви', "id": 8}), + sukkotDateStart = new Date("October 3, 2012 00:00:00"), + sukkotDateFinish = new Date("October 3, 2012 23:59:59"), + sukkot = new Event({"start": sukkotDateStart, "end": sukkotDateFinish, "name": 'Парад любви', "id": 9}), + fishFestivalDateStart = new Date("October 15, 2012 00:00:00"), + fishFestivalDateFinish = new Date("October 15, 2012 23:59:59"), + fishFestival = new Event({"start": fishFestivalDateStart, "end": fishFestivalDateFinish, "name": 'Фестиваль рыбы', "id": 10}), + chocolateFestivalDateStart = new Date("October 19, 2012 00:00:00"), + chocolateFestivalDateFinish = new Date("October 28, 2012 23:59:59"), + chocolateFestival = new Event({"start": chocolateFestivalDateStart, "end": chocolateFestivalDateFinish, "name": 'Фестиваль "Еврошоколад"', "id": 11}), + digitalArtFestivalDateStart = new Date("September 19, 2012 00:00:00"), + digitalArtFestivalDateFinish = new Date("September 28, 2012 23:59:59"), + digitalArtFestival = new Event({"start": digitalArtFestivalDateStart, "end": digitalArtFestivalDateFinish, "name": 'Фестиваль цифрового исскуства', "id": 12}), + fatherDaysDateStart = new Date("September 18, 2012 00:00:00"), + fatherDaysDateFinish = new Date("September 19, 2012 23:59:59"), + fatherDays = new Event({"start": fatherDaysDateStart, "end": fatherDaysDateFinish, "name": 'Дни наследия', "id": 13}), + bearWeekendDateStart = new Date("September 18, 2012 00:00:00"), + bearWeekendDateFinish = new Date("September 19, 2012 23:59:59"), + bearWeekend = new Event({"start": bearWeekendDateStart, "end": bearWeekendDateFinish, "name": 'Bear Weekends', "id": 14}), + teaFestivalDateStart = new Date("September 1, 2012 00:00:00"), + teaFestivalDateFinish = new Date("September 1, 2012 23:59:59"), + teaFestival = new Event({"start": teaFestivalDateStart, "end": teaFestivalDateFinish, "name": 'Фестиваль Чая', "id": 15}), + programmerDayDateStart = new Date("September 13, 2012 00:00:00"), + programmerDayDateFinish = new Date("September 13, 2012 23:59:59"), + programmerDay = new Event({"start": programmerDayDateStart, "end": programmerDayDateFinish, "name": 'День программмиста', "id": 16}), + knowDayDateStart = new Date("September 1, 2012 00:00:01"), + knowDayDateDateFinish = new Date("September 1, 2012 23:59:59"), + knowDayDate = new Event({"start": knowDayDateStart, "end": knowDayDateDateFinish, "name": 'День знаний', "id": 17}), + teacherDayDateStart = new Date("October 5, 2012 00:00:00"), + teacherDayDateFinish = new Date("October 5, 2012 23:59:59"), + teacherDay = new Event({"start": teacherDayDateStart, "end": teacherDayDateFinish, "name": 'День учителя', "id": 18}), + securiteDayDateStart = new Date("November 5, 2012 00:00:00"), + securiteDayDateFinish = new Date("November 5, 2012 23:59:59"), + securiteDay = new Event({"start": securiteDayDateStart, "end": securiteDayDateFinish, "name": 'День защиты информации', "id": 19}), + nationUnitionDateStart = new Date("November 4, 2012 00:00:00"), + nationUnitionDateDateFinish = new Date("November 4, 2012 23:59:59"), + nationUnition = new Event({"start": nationUnitionDateStart, "end": nationUnitionDateDateFinish, "name": 'День нароного единства', "id": 20}); + bestOfSweets.setLocation({"gps": { + "x": 15, "y": 189}, "name": "Австрия, Бургенланд - Айзенштадте, Фестиваль сладких вин"}); bestOfSweets.leaveMark(2); - сirioDeNazare.setLocation({gps :{x : 45, y : 133, name : "Бразилия, Белен, Фестиваль Cirio De Nazare"}}); + сirioDeNazare.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Бразилия, Белен, Фестиваль Cirio De Nazare"}); сirioDeNazare.leaveMark(1); - vinesDay.setLocation({gps :{x : 45, y : 133, name : "Венгрия, Мор, День вина"}}); + vinesDay.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Венгрия, Мор, День вина"}); vinesDay.leaveMark(5); - theBlackCountry.setLocation({gps :{x : 45, y : 133, name : "Великобритания, Дадли, Вкус 'Черной страны'"}}); + theBlackCountry.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Великобритания, Дадли, Вкус 'Черной страны'"}); theBlackCountry.leaveMark(3); - oktoberFest.setLocation({gps :{x : 45, y : 133, name : "Германия, Мюнхен, OktoberFest"}}); + oktoberFest.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Германия, Мюнхен, OktoberFest"}); oktoberFest.leaveMark(1); - programmerDay.parties = [{name: "Pupkin"}, {name: "Alex.IDontKnow"}]; - francfurtBook.setLocation({gps :{x : 45, y : 133, name : "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"}}); + programmerDay.parties = [{name: "Pupkin"}, {"name": "Alex.IDontKnow"}]; + francfurtBook.setLocation({"gps": { + x : 45, y : 133}, "name" : "Германия, Frankfurt, Франкфуртская международная книжная ярмарка"}); francfurtBook.leaveMark(1); - aida.setLocation({gps :{x : 45, y : 133, name : "Египет, ?, Аида у великих пирамид, Гиза"}}); + aida.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Египет, ?, Аида у великих пирамид, Гиза"}); aida.leaveMark(3); - paradeOfLove.setLocation({gps :{x : 45, y : 133, name : "Израль, Тель-Авиве, Парад любви"}}); + paradeOfLove.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Израль, Тель-Авиве, Парад любви"}); paradeOfLove.leaveMark(1); - sukkot.setLocation({gps :{x : 45, y : 133, name : "Израль, Иерусалиме, праздник Суккот"}}); + sukkot.setLocation({"gps": { + "x": 45, y : 133}, "name": "Израль, Иерусалиме, праздник Суккот"}); sukkot.leaveMark(4); - fishFestival.setLocation({gps :{x : 45, y : 133, name : "Испания, О Грове, Фестиваль рыбы"}}); + fishFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Испания, О Грове, Фестиваль рыбы"}); fishFestival.leaveMark(5); - chocolateFestival.setLocation({gps :{x : 45, y : 133, name : 'Италия, Перуджа, Фестиваль "Еврошоколад"'}}); + chocolateFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": 'Италия, Перуджа, Фестиваль "Еврошоколад"'}); chocolateFestival.leaveMark(1); - digitalArtFestival.setLocation({gps :{x : 45, y : 133, name : "Австрия, Линц, Фестиваль Цифрового Исскуства"}}); + digitalArtFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Австрия, Линц, Фестиваль Цифрового Исскуства"}); digitalArtFestival.leaveMark(3); - fatherDays.setLocation({gps :{x : 45, y : 133, name : "Бельгия, Антверпене, Дни наследия"}}); + fatherDays.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Бельгия, Антверпене, Дни наследия"}); fatherDays.leaveMark(4); - bearWeekend.setLocation({gps :{x : 45, y : 133, name : "Бельгия, Брюссель, Bear Weekends"}}); + bearWeekend.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Бельгия, Брюссель, Bear Weekends"}); bearWeekend.leaveMark(2); - teaFestival.setLocation({gps :{x : 45, y : 133, name : "Россия, Москва, Фестиваль чая"}}); - programmerDay.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День программиста"}}); - programmerDay.parties = [{name: "Alexander.Mangin"}, {name: "Alex.IDontKnow"}]; - knowDayDate.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День знаний"}}); - teacherDay.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День учителя"}}); - securiteDay.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День защиты информации"}}); - nationUnition.setLocation({gps :{x : 45, y : 133, name : "Вселенная, Земля, День народного единства"}}); - return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook + teaFestival.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Россия, Москва, Фестиваль чая"}); + programmerDay.setLocation({"gps" :{ + "x": 45, "y": 133}, "name": "Вселенная, Земля, День программиста"}); + programmerDay.parties = [{name: "Alexander.Mangin"}, {"name": "Alex.IDontKnow"}]; + knowDayDate.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День знаний"}); + teacherDay.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День учителя"}); + securiteDay.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День защиты информации"}); + nationUnition.setLocation({"gps": { + "x": 45, "y": 133}, "name": "Вселенная, Земля, День народного единства"}); +return new BaseEvent([bestOfSweets, сirioDeNazare, vinesDay, theBlackCountry, oktoberFest, francfurtBook , aida, paradeOfLove, sukkot, fishFestival, chocolateFestival, digitalArtFestival, fatherDays, bearWeekend, teaFestival, programmerDay, knowDayDate, teacherDay, securiteDay, nationUnition]); } \ No newline at end of file diff --git a/Task/test/CollectionTest.js b/Task/test/CollectionTest.js index 7826181..774b3dd 100644 --- a/Task/test/CollectionTest.js +++ b/Task/test/CollectionTest.js @@ -1,72 +1,76 @@ -module("Конструктор"); -test("Конструктор", function() { - "use strict"; - var newCollection = new Collection([1,2,3,4]); - deepEqual(newCollection.items,[1,2,3,4]); +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global deepEqual: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +/*global Collection: true*/ +module("Конструктор"); +test("Конструктор", function () { + "use strict"; + var newCollection = new Collection([1, 2, 3, 4]); + deepEqual(newCollection.items, [1, 2, 3, 4]); }); module("Add(model)"); -test("Добавление элемента в пустую коллекцию", function() { - "use strict"; - var newCollection = new Collection(); - newCollection = newCollection.add(1); - deepEqual(newCollection.items,[1]); -}) -test("Добавление элемента в не пустую коллекцию", function() { - "use strict"; - var newCollection = new Collection([2]); - newCollection = newCollection.add(1); - deepEqual(newCollection.items,[2, 1]); -}) +test("Добавление элемента в пустую коллекцию", function () { + "use strict"; + var newCollection = new Collection(); + newCollection = newCollection.add(1); + deepEqual(newCollection.items, [1]); +}); +test("Добавление элемента в не пустую коллекцию", function () { + "use strict"; + var newCollection = new Collection([2]); + newCollection = newCollection.add(1); + deepEqual(newCollection.items, [2, 1]); +}); module("filter(function)"); -test("Пример использование filter", function() { - "use strict"; - var newCollection = new Collection([1,2,3,4,5,6]); - newCollection = newCollection.filter(function(element){return (element % 2 === 0)}); - - deepEqual(newCollection.items,[2, 4, 6]); -}) -module("sortBy(function)"); -test("С использование своего компаратора, без инвертирования результата", function() { - "use strict"; - var newCollection = new Collection([{"id" : 8}, {"id" : 2}, {"id" : 3}, - {"id" : 4}, {"id" : 14}, {"id" : 9}]); - var comparator = function (a, b) { - if (a.id > b.id) { - return 1; - } - if (a.id < b.id) { - return -1; - } - return 0; - }; - newCollection = newCollection.sortBy(comparator); - - deepEqual(newCollection.items,[{"id" : 2}, {"id" : 3}, {"id" : 4}, - {"id" : 8}, {"id" : 9}, {"id" : 14}]); -}) -test("С использование своего компаратора, c инвертированием результата", function() { - "use strict"; - var newCollection = new Collection([{"id" : 8}, {"id" : 2}, {"id" : 3}, - {"id" : 4}, {"id" : 14}, {"id" : 9}]); - var comparator = function (a, b) { - if (a.id > b.id) { - return 1; - } - if (a.id < b.id) { - return -1; - } - return 0; - }; - newCollection = newCollection.sortBy(comparator, true); - - deepEqual(newCollection.items,[{"id" : 14}, {"id" : 9}, {"id" : 8}, - {"id" : 4}, {"id" : 3}, {"id" : 2}]); -}) +test("Пример использование filter", function () { + "use strict"; + var newCollection = new Collection([1, 2, 3, 4, 5, 6]); + newCollection = newCollection.filter(function (element) {return (element % 2 === 0); }); -test("Сортировка по default", function() { - "use strict"; - var newCollection = new Collection([3, 2, 1]); - newCollection = newCollection.sortBy(); - - deepEqual(newCollection.items,[1, 2, 3]); -}) \ No newline at end of file + deepEqual(newCollection.items, [2, 4, 6]); +}); +module("sortBy(function)"); +test("С использование своего компаратора, без инвертирования результата", function () { + "use strict"; + var newCollection = new Collection([{"id": 8}, {"id": 2}, {"id": 3}, + {"id": 4}, {"id": 14}, {"id": 9}]), + comparator = function (a, b) { + if (a.id > b.id) { + return 1; + } + if (a.id < b.id) { + return -1; + } + return 0; + }; + newCollection = newCollection.sortBy(comparator); + deepEqual(newCollection.items, [{"id": 2}, {"id": 3}, {"id": 4}, + {"id": 8}, {"id": 9}, {"id": 14}]); +}); +test("С использование своего компаратора, c инвертированием результата", function () { + "use strict"; + var newCollection = new Collection([{"id": 8}, {"id": 2}, {"id": 3}, + {"id": 4}, {"id": 14}, {"id": 9}]), + comparator = function (a, b) { + if (a.id > b.id) { + return 1; + } + if (a.id < b.id) { + return -1; + } + return 0; + }; + newCollection = newCollection.sortBy(comparator, true); + deepEqual(newCollection.items, [{"id": 14}, {"id": 9}, {"id": 8}, + {"id": 4}, {"id": 3}, {"id": 2}]); +}); +test("Сортировка по default", function () { + "use strict"; + var newCollection = new Collection([3, 2, 1]); + newCollection = newCollection.sortBy(); + deepEqual(newCollection.items, [1, 2, 3]); +}); \ No newline at end of file diff --git a/Task/test/EventTest.js b/Task/test/EventTest.js index 619ba53..8d931e8 100644 --- a/Task/test/EventTest.js +++ b/Task/test/EventTest.js @@ -1,34 +1,44 @@ -module("Tests of Event's constructor"); +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global deepEqual: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +/*global Collection: true*/ +/*global throws: true*/ +module("Tests of Event's constructor"); test('Create event', function () { "use strict"; var dateToString = function (currentTime) { var month = currentTime.getMonth() + 1, day = currentTime.getDate(), year = currentTime.getFullYear(); return month + "/" + day + "/" + year; - }, currentTime = new Date(), testEvent = new Event({"start":currentTime}); + }, currentTime = new Date(), testEvent = new Event({"start": currentTime}); equal(dateToString(testEvent.start), dateToString(currentTime)); testEvent = new Event({"start": new Date(1), "end": new Date(2)}); ok(testEvent.start.getTime() < testEvent.end.getTime()); - - throws( - function (){new Event({"start": new Date(2), "end": new Date(1)})}, + throws(function () { + new Event({"start": new Date(2), "end": new Date(1)}); + }, 'Error("Даты начала и конца перепутаны")' - ); - throws( - function (){new Event({"cost":-1})}, + ); + throws(function () { + new Event({"cost": -1}); + }, 'Error("Цена за вход не может быть отрицательной")' - ); - throws( - function (){new Event({"parties":"NoArray"})}, + ); + throws(function () { + new Event({"parties": "NoArray"}); + }, 'Error("Участники - это массив")' - ); - throws( - function (){new Event({"parties":["sds"]})}, + ); + throws(function () { + new Event({"parties": ["sds"]}); + }, 'Error("У одного из участников нет поля <ИМЯ>")' - ); - equal(new Event({"stars":2}).stars, 2,"При присваивании звезд произошла ошибка" ); - equal(new Event({"stars":2.1}).stars, 2,"Функция устанавливающая звездочки не сработала" ); - - + ); + equal(new Event({"stars": 2}).stars, 2, "При присваивании звезд произошла ошибка"); + equal(new Event({"stars": 2.1}).stars, 2, "Функция устанавливающая звездочки не сработала"); }); module("LeaveMark(number)"); @@ -72,46 +82,46 @@ test('Передача дробного числа', function () { module("SetLocation(location)"); test('Gps - undef', function () { "use strict"; - var testEvent = new Event({}),gps; - testEvent.setLocation(gps,""); + var testEvent = new Event({}), gps; + testEvent.setLocation(gps, ""); deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "GPS - некорректный => установить значения по умолчанию"); + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); }); test('Передача числа болешьшего 5', function () { "use strict"; - var testEvent = new Event({}),gps; - testEvent.setLocation(gps,""); + var testEvent = new Event({}), gps; + testEvent.setLocation(gps, ""); deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "GPS - некорректный => установить значения по умолчанию"); + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "GPS - некорректный => установить значения по умолчанию"); }); test('Передача объекта не являющимся gps', function () { "use strict"; var testEvent = new Event({}); - testEvent.setLocation("Not gps",""); + testEvent.setLocation("Not gps", ""); deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "GPS - не содержит X или Y => установить значения по умолчанию"); + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); }); test('Имя места - не строка', function () { "use strict"; var testEvent = new Event({}); - testEvent.setLocation({"x": 0,"y": 0},[]); + testEvent.setLocation({"x": 0, "y": 0}, []); deepEqual(testEvent.location, { - "gps" : {"x": 0,"y": 0}, - "nameLocation" : "Earth" - }, "Название места не строка => установить значения по умолчанию"); + "gps": {"x": 0, "y": 0}, + "nameLocation": "Earth" + }, "Название места не строка => установить значения по умолчанию"); }); test('Корректный тест', function () { "use strict"; var testEvent = new Event({}); - testEvent.setLocation({"x": 1,"y": 2},"Moon"); + testEvent.setLocation({"x": 1, "y": 2}, "Moon"); deepEqual(testEvent.location, { - "gps" : {"x": 1,"y": 2}, - "nameLocation" : "Moon" - }, "GPS - не содержит X или Y => установить значения по умолчанию"); -}); + "gps": {"x": 1, "y": 2}, + "nameLocation": "Moon" + }, "GPS - не содержит X или Y => установить значения по умолчанию"); +}); \ No newline at end of file diff --git a/Task/test/ModelTest.js b/Task/test/ModelTest.js index 456d1ee..81fa2b9 100644 --- a/Task/test/ModelTest.js +++ b/Task/test/ModelTest.js @@ -1,17 +1,27 @@ -module("Create model") +/*global module: true*/ +/*global test: true*/ +/*global ok: true*/ +/*global equal: true*/ +/*global deepEqual: true*/ +/*global initTestBase: true*/ +/*global Event: true*/ +/*global Collection: true*/ +/*global Model: true*/ +/*global TestObject: true*/ +module("Create model"); test('Проверка конструктора клонирования', function () { - "use strict"; + "use strict"; var model = new Model(new TestObject(1)); equal(typeof model["myNumber"], "number", "Личный объект не скопировался"); equal(typeof model["commonNumber"], "number", "Объекты прототипа не скопировались"); }); test('Проверка метода get()', function () { "use strict"; - var model = new Model(new TestObject(1)); - equal(model.get("commonNumber"),20,"Нет доступа к полям прототипа"); - equal(model.get("myNumber"),1,"Нет доступа к личным полям"); - equal(typeof model.get({}),"undefined","Объект не исполняет интерфейс"); - equal(typeof model.get("ТакогоПоляТочноНет"),"undefined","несуществующее поле определено"); + var model = new Model(new TestObject(1)); + equal(model.get("commonNumber"), 20, "Нет доступа к полям прототипа"); + equal(model.get("myNumber"), 1, "Нет доступа к личным полям"); + equal(typeof model.get({}), "undefined", "Объект не исполняет интерфейс"); + equal(typeof model.get("ТакогоПоляТочноНет"), "undefined", "несуществующее поле определено"); }); test('Проверка метода set()', function () { "use strict"; @@ -19,14 +29,15 @@ test('Проверка метода set()', function () { model.set({"myNumber": 2}); equal(typeof model.get("myNumber"), "number", "Присваение произошло с ошибкой"); equal(model.get("myNumber"), 2, "Присвоение произошло с ошибкой"); - model.set({"commonNumber":2}); + model.set({"commonNumber": 2}); equal(TestObject.prototype.commonNumber, 20, "Присвоение испортило прототип"); equal(model.get("commonNumber"), 2, "Ошибка при присвоении наследуемому полю через прототип"); }); function TestObject (number) { - this.myNumber = number; - } + "use strict"; + this.myNumber = number; +} TestObject.prototype.commonNumber = 20; From 6dd4ff0b42a59206d6bffc0ac2dffdb060bbe57b Mon Sep 17 00:00:00 2001 From: "Mangin.Alexander" Date: Thu, 1 Nov 2012 21:18:55 +0600 Subject: [PATCH 16/16] Add JSDoc --- Task/BaseEvent.js | 4 ++-- Task/Collection.js | 33 +++++++++++---------------------- Task/Model.js | 26 ++++++++++++-------------- Task/event.js | 3 ++- 4 files changed, 27 insertions(+), 39 deletions(-) diff --git a/Task/BaseEvent.js b/Task/BaseEvent.js index 1780c98..b5eed43 100644 --- a/Task/BaseEvent.js +++ b/Task/BaseEvent.js @@ -1,8 +1,8 @@ /*global Collection: true*/ /** - * Shell for "sql" operations with Array Events. - * + * Shell for "sql" operations with Array Events. + * @prototype {Collection} * @constructor * @method {pastEventBase} - Создает BaseEvent с пропущенными событиями * @method {pastEventBase} - Создает BaseEvent с грядущими событиями diff --git a/Task/Collection.js b/Task/Collection.js index 4fc0a34..5bba66f 100644 --- a/Task/Collection.js +++ b/Task/Collection.js @@ -1,4 +1,14 @@ /*global Collection: true*/ + +/** + * 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) { "use strict"; var item; @@ -9,36 +19,16 @@ Collection = function (otherItems) { } } }; - -/** - * @param {obj} - * @help Создает коллекцию со старыми элементами текущей коллекции + новый элемент. - * @return {Collection} - */ Collection.prototype.add = function (obj) { "use strict"; var newEvents = this.items.concat([obj]); return new Collection(newEvents); }; -/** - * @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"; var newItems = this.items.filter(selector); return new Collection(newItems); }; -/** - * @return {Collection} - */ Collection.prototype.sortBy = function (comparator, isInvert) { "use strict"; var newItems = [].concat(this.items); @@ -57,5 +47,4 @@ Collection.prototype.sortBy = function (comparator, isInvert) { newItems.sort(); } return new Collection(newItems); -}; -// Другие необходимые вам поля \ No newline at end of file +}; \ No newline at end of file diff --git a/Task/Model.js b/Task/Model.js index 2aab8b5..79e2dc0 100644 --- a/Task/Model.js +++ b/Task/Model.js @@ -1,16 +1,20 @@ -var Model = function (data) { + +/** + * 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 + */ +var Model = function (data) { "use strict"; var nameField; for (nameField in data) { this[nameField] = data[nameField]; } }; -/** - * @param {Object} attributes - * - * @example - * item.set({title: "March 20", content: "In his eyes she eclipses..."}); - */ Model.prototype.set = function (attributes) { "use strict"; var nameAttr; @@ -22,9 +26,6 @@ Model.prototype.set = function (attributes) { } } }; -/** - * @param {String} attribute - */ Model.prototype.get = function (attribute) { "use strict"; if (typeof attribute !== 'string' || typeof this[attribute] === "undefined") { @@ -32,10 +33,7 @@ Model.prototype.get = function (attribute) { } return this[attribute]; }; -/** - * @param {Object} attributes - */ -Model.prototype.validate = function (attributes) { +Model.prototype.validate = function () { "use strict"; throw new Error('this is Abstract method'); }; \ No newline at end of file diff --git a/Task/event.js b/Task/event.js index d554cc5..d0b7848 100644 --- a/Task/event.js +++ b/Task/event.js @@ -2,6 +2,7 @@ /** * Creates an instance of Event. * + * @prototype {Model} * @param {data} - is start event * @field {start} - is start event * @field {end} - is end event @@ -11,7 +12,7 @@ * @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 - допустимые значения) + * @method {leaveMark} - is setter for stars's field (0,1,2,3,4,5 - validate value) */ function Event(data) { "use strict";