-
Notifications
You must be signed in to change notification settings - Fork 0
add jsfunc #5
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
base: master
Are you sure you want to change the base?
add jsfunc #5
Conversation
task4/js/script.js
Outdated
| console.log("Нельзя вывести столько постов. Промежуток вывода не совпадает с количеством постов"); | ||
| } | ||
| else{ | ||
| var sortedArrOfPosts = []; |
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.
- А где фильтрация то ??
- Array.prototype.sort, Array.prototype.filter etc изучить и использовать
task4/js/script.js
Outdated
| for(var i=0;i<photoPosts.length;i++){ | ||
| if(photoPosts[i].id == idOfPost) return photoPosts[i]; | ||
| } | ||
| return "Пост не найден"; |
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.
Тестовый аутпут в консоль такой можно, но вот результат функции всетаки не должен быть "от мишки до книжки". Четко либо пост, либо его отсутствие null (что тоже кстати typeof null === 'object')
task4/js/script.js
Outdated
| } | ||
|
|
||
| function getPhotoPost(idOfPost){ | ||
| for(var i=0;i<photoPosts.length;i++){ |
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.
task4/js/script.js
Outdated
| } | ||
|
|
||
| function validatePhotoPost(postForCheck){ | ||
| if(postForCheck.id == null) { |
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.
а если оно undefined, {}, [1, 2, 3] или любая другая лабуда?
тут как в Java не прокатит :)
проверяем либо на тип
либо говорим что на совести программиста и проверяем что оно есть (но не в этом конкретном варианте)
task4/js/script.js
Outdated
| console.log("Пустое поле id"); | ||
| return false;} | ||
|
|
||
| for(var i=0;i < photoPosts.length;i++){ |
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.
Array.prototype.some
task4/js/script.js
Outdated
| return false; | ||
| } | ||
| } | ||
| if(postForCheck.description == null || postForCheck.description.length>200) { |
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.
Читаем про == и ===
и помним что лучше == не использовать
task4/js/script.js
Outdated
| console.log("Неверный description"); | ||
| return false; | ||
| } | ||
| if(postForCheck.author == null || postForCheck.author == "") { |
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.
if (!postForCheck.author) - как пример
task4/js/script.js
Outdated
| } | ||
|
|
||
| function addPhotoPost(newPost){ | ||
| if(validatePhotoPost(newPost) == false) return false; |
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.
сравнивать boolean не надо !
if (isValid(post)) {
posts.push(post);
return true;
}
task4/js/script.js
Outdated
| } | ||
|
|
||
| function editPhotoPost(idForEd, postForEd){ | ||
| for(var i=0; i<photoPosts.length;i++){ |
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.
Array.prototype.find
А дальше вспоминаем что вернется референс и его можно менять
task4/js/script.js
Outdated
| } | ||
|
|
||
| function removePhotoPost(idForRem){ | ||
| for(var i=0;i<photoPosts.length;i++){ |
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.
опять же Array.prototype.find
task4/js/script.js
Outdated
| @@ -0,0 +1,290 @@ | |||
| (function() { | |||
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.
За отступами следим пожалуйста , если пользуемся WebStorm/Idea то выделяем все и Ctrl-Alt-L.
Если что другое то следим сами или ставим плагинчики на автоформат.
task4/js/script.js
Outdated
|
|
||
| function removePhotoPost(idForRem){ | ||
| var postOfId = getPhotoPost(idForRem); | ||
| postOfId.postVisibility = false; |
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.
А где проверка что postOfId не null ?
Почему "Пост для удаления не найден" в любом случае?
и результат почему лож в любом случае?
task4/js/script.js
Outdated
| } | ||
|
|
||
| function addPhotoPost(newPost){ | ||
| if(!validatePhotoPost(newPost)) return false; |
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.
Скобочки блока { }
стараемся ставить всегда, это уменьшает вероятность ошибиться и считается правилом хорошего тона.
task4/js/script.js
Outdated
| if(!postOfId) { | ||
| return false; | ||
| } | ||
| if(postForEd.description){ |
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.
Можно конечно и так до первой проверки, но это как-то странненько,
у нас есть validate для поста, почему бы его не заюзать, единственный вопрос как не попортить данные в случае чего - делаем копию.
Копию можно сделать используя ES6 фитчу
let copy = Object.assign({}, obj);
либо для сериализуемых объектов можем сделать deepCoppy:
var copy = JSON.parse(JSON.stringify(obj));
либо руками делаем (отдельный метод)
где ручками копируем как нам надо филд за филдом.
task4/js/script.js
Outdated
| } | ||
| else{ | ||
| var sortedArrOfPosts = photoPosts; | ||
| sortedArrOfPosts = sortedArrOfPosts.slice(postStart, number+postStart).sort(dateComparator); |
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.
Сначала фильтруем потом отрезаем, наоборот это не то что ожидается от этой функции
task4/js/script.js
Outdated
| return post.createdAt === filterConfig.createdAt; | ||
| }); | ||
| } | ||
| sortedArrOfPosts = sortedArrOfPosts.slice(postStart, number + postStart).sort(dateComparator); |
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.
сортируем тоже раньше чем обрезаем выборку.
task4/js/script.js
Outdated
| } | ||
|
|
||
| function dateComparator(date1, date2) { | ||
| return date1.createdAt - date2.createdAt; |
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.
post1, post2 тут скорее.
task4/js/script.js
Outdated
|
|
||
| function editPhotoPost(idForEd, postForEd) { | ||
| var postOfId = getPhotoPost(idForEd); | ||
| if (!validatePhotoPost(postOfId)) { |
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.
нужно предусмотреть момент с отключением проверки на уникальность id, или вообще вынести её отдельно, сейчас тут будет валится векгда - это раз
зачем проверять пост который уже в базе? - это два
task4/js/script.js
Outdated
| } | ||
| var postCopy = JSON.parse(JSON.stringify(postOfId)); | ||
| if (postForEd.description) { | ||
| if (typeof postForEd.description !== "string" || postForEd.description.length > 200 || postForEd.description === "") { |
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.
смысл с комментарием про validate был в том чем:
мы делаем копию нужного поста, без проверок меняем его в соответствии с проброшенным объектом
после этого делаем validate, и если с копией все ок, заменяем оригинал на полученную копию в базе.
task4/js/script.js
Outdated
| } | ||
| postCopy.hashTags = postForEd.hashTags; | ||
| } | ||
| clonePost(postOfId, postCopy); |
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.
можно и так, но луше почитать про Object.assign, ну либо уже использовать этот метод тогда везде, например для создания копии делать так clonePost({}, originPost);
task4/js/script.js
Outdated
| } | ||
|
|
||
| function clonePost(post1, post2){ | ||
| if(post2.description){ |
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.
А зачем проверки? Clone это clone .
Хотя это кстати не совсем clone.
| sortedArrOfPosts = sortedArrOfPosts.filter(function (post) { | ||
| return post.createdAt === filterConfig.createdAt; | ||
| }); | ||
| } |
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.
Еще фильтрация по хэштегам...
| return false; | ||
| } | ||
|
|
||
| if (typeof postForCheck.description !== "string" || postForCheck.description.length > 200 || postForCheck.description === "") { |
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.
return validateForEditing(postForCheck);
No description provided.