-
Notifications
You must be signed in to change notification settings - Fork 9
Четвертое ДЗ #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
turboDi
wants to merge
13
commits into
cripi-javascript:master
Choose a base branch
from
turboDi:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Четвертое ДЗ #11
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
326b57e
1st steps to dz 4
4a992c5
all but everything works
2c25059
almost everything works
c7b3c28
decided to make it my way
9ff6566
updated wrong field names
e20528f
yet another commit
484b43c
Voila
db3c4bc
unused files
78d1f8a
iefe
dd05570
iefe everywhere
eb49721
add validation logic
21bca18
validation msg fix
fb5e6e1
one random event func
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
var Collection = (function () { | ||
'use strict'; | ||
var Collection = function (items) { | ||
var item; | ||
this.items = []; | ||
for (item in items) { | ||
if (items.hasOwnProperty(item)) { | ||
if (items[item].validate().valid) { | ||
this.items.push(items[item]); | ||
} | ||
} | ||
} | ||
}; | ||
|
||
/** | ||
* @return {Collection} | ||
*/ | ||
Collection.prototype = | ||
{ | ||
add : function (model) { | ||
this.items.push(model); | ||
}, | ||
/** | ||
* Фильтрация коллекции по правилам, определенным в функции selector | ||
* | ||
* @param {Function} selector | ||
* | ||
* @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter | ||
* | ||
* @return {Collection} | ||
*/ | ||
filter : function (selector) { | ||
var tmp = this.items.filter(selector); | ||
return new this.constructor(tmp); | ||
}, | ||
/** | ||
* Сортировка коллекции по правилам, определенным в функции selector | ||
* | ||
* @param {Function} selector | ||
* @param {Boolean} desc | ||
* | ||
* @return {Collection} | ||
*/ | ||
sortBy : function (selector, desc) { | ||
this.items.sort(selector); | ||
if (desc) { | ||
this.items.reverse(); | ||
} | ||
return this; | ||
} | ||
}; | ||
return Collection; | ||
}()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
|
||
<meta charset="utf-8"> | ||
<title>EVents test</title> | ||
|
||
</head> | ||
|
||
<body> | ||
|
||
<div class="container"> | ||
|
||
<input type="button" onclick="console.dir(events.findFutureEvents().findThisWeekEvents());" value = "будущие события недели"/> | ||
<input type="button" onclick="console.dir(events.findFutureEvents().findPartyEvents().sortByStartDate());" value = "будущие пьянки, отсортированные по дате"/> | ||
<input type="button" onclick="console.dir(events.findFutureEvents().findThisWeekEvents().findNightAlarms().sortByNextHappenDate());" value = "события, которые меня разбудят на этой неделе"/> | ||
|
||
</div> | ||
|
||
<script src="validation.js"></script> | ||
<script src="model.js"></script> | ||
<script src="collection.js"></script> | ||
<script src="event-model.js"></script> | ||
<script src="event-collection.js"></script> | ||
<script src="utils.js"></script> | ||
|
||
</body> | ||
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
var Events = (function () { | ||
'use strict'; | ||
var Events = function (items) { | ||
Collection.apply(this, arguments); | ||
}; | ||
inherits(Events, Collection); | ||
|
||
Events.prototype.constructor = Events; | ||
/** | ||
* Возвращает новую коллекцию, содержащую только прошедшие события | ||
* @return {Events} | ||
*/ | ||
Events.prototype.findPastEvents = function () { | ||
return this.filter(function (event) { | ||
return event.endDate < new Date(); | ||
}); | ||
}; | ||
/** | ||
* Возвращает новую коллекцию, содержащую только будущие события | ||
* @return {Events} | ||
*/ | ||
Events.prototype.findFutureEvents = function () { | ||
return this.filter(function (event) { | ||
return event.startDate > new Date(); | ||
}); | ||
}; | ||
/** | ||
* Возвращает новую коллекцию, содержащую только события этой недели | ||
* @return {Events} | ||
*/ | ||
Events.prototype.findThisWeekEvents = function () { | ||
return this.filter(function (event) { | ||
return event.startDate > Utils.getWeekStartDate() && event.startDate < Utils.getWeekEndDate(); | ||
}); | ||
}; | ||
/** | ||
* Возвращает новую коллекцию, содержащую только события 'Drunken feast' | ||
* @return {Events} | ||
*/ | ||
Events.prototype.findPartyEvents = function () { | ||
return this.filter(function (event) { | ||
return event.title === 'Drunken feast'; | ||
}); | ||
}; | ||
/** | ||
* Возвращает новую коллекцию, содержащую только те события, напоминание которых сработает ночью | ||
* @return {Events} | ||
*/ | ||
Events.prototype.findNightAlarms = function () { | ||
return this.filter(function (event) { | ||
var alarm = event.getNextAlarmTime(); | ||
return alarm.getHours() > 0 && alarm.getHours() < 8; | ||
}); | ||
}; | ||
/** | ||
* Сортирует коллекцию по дате начала события | ||
* @return {Events} | ||
*/ | ||
Events.prototype.sortByStartDate = function (asc) { | ||
return this.sortBy(function (a, b) { | ||
return a.startDate - b.startDate; | ||
}, asc); | ||
}; | ||
/** | ||
* Сортирует коллекцию по следующей дате периодического события | ||
* @return {Events} | ||
*/ | ||
Events.prototype.sortByNextHappenDate = function (asc) { | ||
return this.sortBy(function (a, b) { | ||
return a.getNextHappenDate() - b.getNextHappenDate(); | ||
}, asc); | ||
}; | ||
return Events; | ||
}()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
var Event = (function () { | ||
'use strict'; | ||
function checkStartDate(date, validator) { | ||
if (date === null) { | ||
date = new Date(); | ||
} else if (!(date instanceof Date && isFinite(date))) { | ||
validator.addError("startDate", "Start date is invalid, check syntax"); | ||
date = null; | ||
} | ||
return date; | ||
} | ||
|
||
function checkEndDate(endDate, startDate, validator) { | ||
var date; | ||
if (endDate === null) { | ||
date = startDate; | ||
if (date !== null) { | ||
date.setHours(startDate.getHours() + 1); | ||
} | ||
} else if (endDate instanceof Date && isFinite(endDate)) { | ||
if (endDate < startDate) { | ||
validator.addError("endDate", "End date should be after start date"); | ||
date = null; | ||
} else { | ||
date = endDate; | ||
} | ||
} else { | ||
validator.addError("endDate", "End date is invalid, check syntax"); | ||
date = null; | ||
} | ||
return date; | ||
} | ||
|
||
function checkRepeat(repeat, validator) { | ||
if (repeat === null) { | ||
repeat = Const.REPEAT.NEVER; | ||
} else if (!(repeat.title && repeat.value)) { | ||
validator.addError("repeat", "Unknown type of 'repeat' variable"); | ||
repeat = null; | ||
} else if (!Utils.checkAddTime(repeat.value)) { | ||
validator.addError("repeat", "Add time in 'repeat' variable must have format '+ dd.MM.YY hh:mm'"); | ||
repeat = null; | ||
} | ||
return repeat; | ||
} | ||
|
||
function checkAlert(alert, validator) { | ||
if (alert === null) { | ||
alert = Const.ALERT.NONE; | ||
} else if (!(alert.title && alert.value)) { | ||
validator.addError("alert", "Unknown type of 'alert' variable"); | ||
alert = null; | ||
} else if (!Utils.checkAddTime(alert.value)) { | ||
validator.addError("alert", "Add time in 'alert' variable must have format '+ dd.MM.YY hh:mm'"); | ||
alert = null; | ||
} | ||
return alert; | ||
} | ||
/** | ||
* Создает объект Event | ||
* | ||
* @param {String} [title="New Event"] Имя события | ||
* @param {String} [location] Место события | ||
* @param {Number|Date} [starts="new Date()"] Начало события | ||
* @param {Number|Date} [ends="starts + 1"] Конец события | ||
* @param {Object} [repeat="Const.REPEAT.NEVER"] Периодичность события | ||
* @param {Object} [alert="Const.ALERT.NONE"] Предупреждение | ||
* @param {String} [notes] Заметки | ||
* | ||
* @example | ||
* new Event({title: "Лекция JavaScript", | ||
* location: "УРГУ", | ||
* startDate: new Date('2011-10-10T14:48:00'), | ||
* endDate: new Date('2011-10-10T15:48:00'), | ||
* repeat: REPEAT.WEEK, | ||
* alert: ALERT.B30MIN, | ||
* notes: "Вспомнить, что проходили на прошлом занятии"}) | ||
* | ||
* @return {Event} | ||
*/ | ||
var Event = function (data) { | ||
Model.apply(this, arguments); | ||
}; | ||
inherits(Event, Model); | ||
|
||
Event.prototype.constructor = Event; | ||
|
||
/** | ||
* Функция, валидирующая объект Event | ||
* | ||
* @return {ValidationResult} | ||
*/ | ||
Event.prototype.validate = function () { | ||
var result = new ValidationResult(true); | ||
this.startDate = checkStartDate(this.startDate, result); | ||
this.endDate = checkEndDate(this.endDate, this.startDate, result); | ||
this.repeat = checkRepeat(this.repeat, result); | ||
this.alert = checkAlert(this.alert, result); | ||
result.log(); | ||
return result; | ||
}; | ||
/** | ||
* Вычисляет когда в следующий раз случится периодическое событие | ||
* | ||
* @return {Date} | ||
*/ | ||
Event.prototype.getNextHappenDate = function () { | ||
var nhd, today; | ||
if (!this.nextHappenDate) { | ||
today = new Date(); | ||
nhd = this.startDate; | ||
while (nhd < today) { | ||
nhd = Utils.addDateTime(nhd, this.repeat.value); | ||
} | ||
this.nextHappenDate = nhd; | ||
} | ||
return this.nextHappenDate; | ||
}; | ||
/** | ||
* Вычисляет следующее время напоминания для периодических событий | ||
* | ||
* @param {Event} event Событие | ||
* | ||
* @return {Date} | ||
*/ | ||
Event.prototype.getNextAlarmTime = function () { | ||
var nhd = this.getNextHappenDate(); | ||
return Utils.addDateTime(nhd, this.alert.value); | ||
}; | ||
/** | ||
* Функция проверяет, нужно ли напомнить о событии | ||
* | ||
* @param {Event} event Событие | ||
* | ||
* @return {Boolean} | ||
*/ | ||
Event.prototype.isAlertTime = function () { | ||
var today, diff; | ||
today = new Date(); | ||
diff = today - this.getNextAlarmTime(); | ||
return diff > -500 && diff < 500; | ||
}; | ||
return Event; | ||
}()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
var Model = (function () { | ||
"use strict"; | ||
var Model = function (data) { | ||
var propName; | ||
for (propName in data) { | ||
if (data.hasOwnProperty(propName)) { | ||
this[propName] = data[propName]; | ||
} | ||
} | ||
|
||
}; | ||
|
||
Model.prototype = | ||
{ | ||
/** Мутатор | ||
* @param {Object} attributes | ||
* | ||
* @example | ||
* item.set({title: "March 20", notes: "In his eyes she eclipses..."}); | ||
*/ | ||
set : function (attributes) { | ||
var attribute; | ||
for (attribute in attributes) { | ||
if (attributes.hasOwnProperty(attribute)) { | ||
this[attribute] = attributes[attribute]; | ||
} | ||
} | ||
}, | ||
/** Аксессор | ||
* @param {String} attribute | ||
*/ | ||
get : function (attribute) { | ||
if (this.hasOwnProperty(attribute)) { | ||
return this[attribute]; | ||
} | ||
}, | ||
/** Валидатор | ||
* @param {Object} attributes | ||
*/ | ||
validate : function (attributes) { | ||
console.log('this is Abstract method'); | ||
} | ||
}; | ||
return Model; | ||
}()); | ||
|
||
function inherits(Constructor, SuperConstructor) { | ||
"use strict"; | ||
var F = function () {}; | ||
F.prototype = SuperConstructor.prototype; | ||
Constructor.prototype = new F(); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можешь поступить как и с утилитами - вынести
"use strict";
в IIFE