Skip to content

Conversation

@Seal98
Copy link
Owner

@Seal98 Seal98 commented Mar 19, 2018

No description provided.

console.log("Нельзя вывести столько постов. Промежуток вывода не совпадает с количеством постов");
}
else{
var sortedArrOfPosts = [];
Copy link

Choose a reason for hiding this comment

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

  1. А где фильтрация то ??
  2. Array.prototype.sort, Array.prototype.filter etc изучить и использовать

for(var i=0;i<photoPosts.length;i++){
if(photoPosts[i].id == idOfPost) return photoPosts[i];
}
return "Пост не найден";
Copy link

Choose a reason for hiding this comment

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

Тестовый аутпут в консоль такой можно, но вот результат функции всетаки не должен быть "от мишки до книжки". Четко либо пост, либо его отсутствие null (что тоже кстати typeof null === 'object')

}

function getPhotoPost(idOfPost){
for(var i=0;i<photoPosts.length;i++){
Copy link

Choose a reason for hiding this comment

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

}

function validatePhotoPost(postForCheck){
if(postForCheck.id == null) {
Copy link

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 не прокатит :)
проверяем либо на тип
либо говорим что на совести программиста и проверяем что оно есть (но не в этом конкретном варианте)

console.log("Пустое поле id");
return false;}

for(var i=0;i < photoPosts.length;i++){
Copy link

Choose a reason for hiding this comment

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

Array.prototype.some

return false;
}
}
if(postForCheck.description == null || postForCheck.description.length>200) {
Copy link

Choose a reason for hiding this comment

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

Читаем про == и ===
и помним что лучше == не использовать

console.log("Неверный description");
return false;
}
if(postForCheck.author == null || postForCheck.author == "") {
Copy link

Choose a reason for hiding this comment

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

if (!postForCheck.author) - как пример

}

function addPhotoPost(newPost){
if(validatePhotoPost(newPost) == false) return false;
Copy link

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;
}

}

function editPhotoPost(idForEd, postForEd){
for(var i=0; i<photoPosts.length;i++){
Copy link

Choose a reason for hiding this comment

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

Array.prototype.find
А дальше вспоминаем что вернется референс и его можно менять

}

function removePhotoPost(idForRem){
for(var i=0;i<photoPosts.length;i++){
Copy link

Choose a reason for hiding this comment

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

опять же Array.prototype.find

@@ -0,0 +1,290 @@
(function() {
Copy link

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.
Если что другое то следим сами или ставим плагинчики на автоформат.


function removePhotoPost(idForRem){
var postOfId = getPhotoPost(idForRem);
postOfId.postVisibility = false;
Copy link

Choose a reason for hiding this comment

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

А где проверка что postOfId не null ?
Почему "Пост для удаления не найден" в любом случае?
и результат почему лож в любом случае?

}

function addPhotoPost(newPost){
if(!validatePhotoPost(newPost)) return false;
Copy link

Choose a reason for hiding this comment

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

Скобочки блока { }
стараемся ставить всегда, это уменьшает вероятность ошибиться и считается правилом хорошего тона.

if(!postOfId) {
return false;
}
if(postForEd.description){
Copy link

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));
либо руками делаем (отдельный метод)
где ручками копируем как нам надо филд за филдом.

}
else{
var sortedArrOfPosts = photoPosts;
sortedArrOfPosts = sortedArrOfPosts.slice(postStart, number+postStart).sort(dateComparator);
Copy link

Choose a reason for hiding this comment

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

Сначала фильтруем потом отрезаем, наоборот это не то что ожидается от этой функции

return post.createdAt === filterConfig.createdAt;
});
}
sortedArrOfPosts = sortedArrOfPosts.slice(postStart, number + postStart).sort(dateComparator);
Copy link

Choose a reason for hiding this comment

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

сортируем тоже раньше чем обрезаем выборку.

}

function dateComparator(date1, date2) {
return date1.createdAt - date2.createdAt;
Copy link

Choose a reason for hiding this comment

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

post1, post2 тут скорее.


function editPhotoPost(idForEd, postForEd) {
var postOfId = getPhotoPost(idForEd);
if (!validatePhotoPost(postOfId)) {
Copy link

Choose a reason for hiding this comment

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

нужно предусмотреть момент с отключением проверки на уникальность id, или вообще вынести её отдельно, сейчас тут будет валится векгда - это раз
зачем проверять пост который уже в базе? - это два

}
var postCopy = JSON.parse(JSON.stringify(postOfId));
if (postForEd.description) {
if (typeof postForEd.description !== "string" || postForEd.description.length > 200 || postForEd.description === "") {
Copy link

Choose a reason for hiding this comment

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

смысл с комментарием про validate был в том чем:
мы делаем копию нужного поста, без проверок меняем его в соответствии с проброшенным объектом
после этого делаем validate, и если с копией все ок, заменяем оригинал на полученную копию в базе.

}
postCopy.hashTags = postForEd.hashTags;
}
clonePost(postOfId, postCopy);
Copy link

Choose a reason for hiding this comment

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

можно и так, но луше почитать про Object.assign, ну либо уже использовать этот метод тогда везде, например для создания копии делать так clonePost({}, originPost);

}

function clonePost(post1, post2){
if(post2.description){
Copy link

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;
});
}
Copy link

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 === "") {
Copy link

Choose a reason for hiding this comment

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

return validateForEditing(postForCheck);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants