Skip to content

add jsfunc#5

Open
Seal98 wants to merge 5 commits into
masterfrom
jsfunc
Open

add jsfunc#5
Seal98 wants to merge 5 commits into
masterfrom
jsfunc

Conversation

@Seal98
Copy link
Copy Markdown
Owner

@Seal98 Seal98 commented Mar 19, 2018

No description provided.

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

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 изучить и использовать

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}

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

Choose a reason for hiding this comment

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

Comment thread task4/js/script.js Outdated
}

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

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

Comment thread task4/js/script.js Outdated
console.log("Пустое поле id");
return false;}

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

Choose a reason for hiding this comment

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

Array.prototype.some

Comment thread task4/js/script.js Outdated
return false;
}
}
if(postForCheck.description == null || postForCheck.description.length>200) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
console.log("Неверный description");
return false;
}
if(postForCheck.author == null || postForCheck.author == "") {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}

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

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

Comment thread task4/js/script.js Outdated
}

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
@@ -0,0 +1,290 @@
(function() {
Copy link
Copy Markdown

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

Comment thread task4/js/script.js Outdated

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
if(!postOfId) {
return false;
}
if(postForEd.description){
Copy link
Copy Markdown

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

Comment thread task4/js/script.js Outdated
}
else{
var sortedArrOfPosts = photoPosts;
sortedArrOfPosts = sortedArrOfPosts.slice(postStart, number+postStart).sort(dateComparator);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
return post.createdAt === filterConfig.createdAt;
});
}
sortedArrOfPosts = sortedArrOfPosts.slice(postStart, number + postStart).sort(dateComparator);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated

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

Choose a reason for hiding this comment

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

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

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

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}
postCopy.hashTags = postForEd.hashTags;
}
clonePost(postOfId, postCopy);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment thread task4/js/script.js Outdated
}

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

Choose a reason for hiding this comment

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

А зачем проверки? Clone это clone .
Хотя это кстати не совсем clone.

Comment thread task4/js/script.js
sortedArrOfPosts = sortedArrOfPosts.filter(function (post) {
return post.createdAt === filterConfig.createdAt;
});
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Еще фильтрация по хэштегам...

Comment thread task4/js/script.js
return false;
}

if (typeof postForCheck.description !== "string" || postForCheck.description.length > 200 || postForCheck.description === "") {
Copy link
Copy Markdown

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.

2 participants