Skip to content

Conversation

@NikitaKir98
Copy link
Contributor

@NikitaKir98 NikitaKir98 commented May 21, 2025

@keksobot keksobot changed the title Выполнил ДЗ по модулю 9.1 Правда или действие May 21, 2025
}
}

function onDescriptionInput () {
Copy link
Contributor

Choose a reason for hiding this comment

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

ожидаются стрелочные функции - надо проверить весь код

Copy link
Contributor Author

Choose a reason for hiding this comment

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

убрал фанкшен декларейшен

const validateDescription = (value) => {
errorMessage = '';

const inputText = value;
Copy link
Contributor

Choose a reason for hiding this comment

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

с большей вероятностью, нет необходимости в новой константе - используем имеющуюся

Copy link
Contributor Author

Choose a reason for hiding this comment

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

убрал константу

@@ -0,0 +1,33 @@
const DESCRIPTION_SYMBOLS_MAX = 140;

let errorMessage = '';
Copy link
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Contributor Author

Choose a reason for hiding this comment

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

убрал переменную, сделал обьект

}
];

return rules.every((rule) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Можно вернуть код ошибки, если она есть или false (null), если ошибки нет

Copy link
Contributor Author

Choose a reason for hiding this comment

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

функция переделана

});
};

const errorDescription = () => errorMessage;
Copy link
Contributor

Choose a reason for hiding this comment

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

ошибку удобнее получить от функции валидации

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправлено на const getError = (field) => () => errors[field]

const errorDescription = () => errorMessage;


export { validateDescription, errorDescription };
Copy link
Contributor

Choose a reason for hiding this comment

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

функции валидации удобнее размесить в одном модуле validate.js

Copy link
Contributor Author

Choose a reason for hiding this comment

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

обьединил модули

return true;
}

const rules = [
Copy link
Contributor

Choose a reason for hiding this comment

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

Вот это можно обсудить, чтобы реализовать более оптимальное решение

Copy link
Contributor Author

Choose a reason for hiding this comment

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

обсудили, исправили

function onHashtagsInput () {
if (pristine.validate()) {
imgUploadSubmit.disabled = false;
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

секция else избыточная

if (условие) {
  // действие
  return
}
// действие

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправил

}

const onDocumentKeydown = (event) => {
if (isEscapeKey(event)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

сначала отсекаем ненужные кейсы

if (!isEscapeKey) {
  return;
}

После упрощаем условие, отсекая else

Copy link
Contributor Author

Choose a reason for hiding this comment

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

поправил немного по другому, нужно проверить

Copy link
Contributor Author

Choose a reason for hiding this comment

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

через тернарный оператор

const onDocumentKeydown = (event) => {
if (isEscapeKey(event)) {
if (document.activeElement === inputHashtags || document.activeElement === inputDescription) {
event.stopPrepagation();
Copy link
Contributor

Choose a reason for hiding this comment

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

Точно ли необходимо останавливать распространение? Если не убрать, на что может повлиять?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

сделал без stopPrepagation();

const body = document.querySelector('body');
const overlayForm = document.querySelector('.img-upload__overlay');
const closeBtnForm = overlayForm.querySelector('.img-upload__cancel');
const UploadForm = document.querySelector('.img-upload__form');
Copy link
Contributor

Choose a reason for hiding this comment

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

Именование констант и переменных начинается со строчных букв - camelCase.
С прописных именуются компоненты и классы - PascalCase
Неизменные константы пишем прописными - UPPER_CASE

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправил

const UploadForm = document.querySelector('.img-upload__form');
const inputDescription = UploadForm.querySelector('.text__description');
const inputHashtags = UploadForm.querySelector('.text__hashtags');
const UploadSubmit = UploadForm.querySelector('.img-upload__submit');
Copy link
Contributor

Choose a reason for hiding this comment

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

Именование констант и переменных начинается со строчных букв - camelCase.
С прописных именуются компоненты и классы - PascalCase
Неизменные константы пишем прописными - UPPER_CASE

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправил

if (pristine.validate()) {
UploadSubmit.disabled = false;
return;
} UploadSubmit.disabled = true;
Copy link
Contributor

Choose a reason for hiding this comment

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

Новая команда после условия - полезно разместить с новой строки

} UploadSubmit.disabled = true;
};

const onDocumentKeydown = (event) => isEscapeKey(event) && (document.activeElement === inputHashtags || document.activeElement === inputDescription ? event.stopPropagation() : closeFormUpload());// eslint-disable-line
Copy link
Contributor

Choose a reason for hiding this comment

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

Полезно отменять конкретное правило линтера. Если строка длинная, можно попробовать корректно перенести условия

Copy link
Contributor

Choose a reason for hiding this comment

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

В данной ситуации удобнее использовать условие if:

  • от этой функции не ожидается возвращаемый результат - т.е., return в ней не требуется
  • вызываемые в тернарном операторе функции тоже не возвращают какой-либо результат

В таких случаях:

if (условие) {
  действиеА
  return;
}
действиеБ

Copy link
Contributor

Choose a reason for hiding this comment

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

Есть ли необходимость останавливать распространение события?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправил с if, но нужно обсудить

Copy link
Contributor Author

Choose a reason for hiding this comment

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

функция переписана без остановки события и без тернарного оператора


const onDocumentKeydown = (event) => isEscapeKey(event) && (document.activeElement === inputHashtags || document.activeElement === inputDescription ? event.stopPropagation() : closeFormUpload());// eslint-disable-line

const onClickCloseBtnForm = () => closeFormUpload();// eslint-disable-line
Copy link
Contributor

Choose a reason for hiding this comment

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

Так же - полезно указать, какое правило отменяется. Сейчас неочевидна причина отмены

Copy link
Contributor

Choose a reason for hiding this comment

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

Можем использовать closeFormeUpload без этой функции?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

тогда в функции closeFormeUpload, она будет использовать сама себя

Copy link
Contributor Author

Choose a reason for hiding this comment

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

теперь причина отмены понятна, функция сделана через if

Copy link
Contributor Author

Choose a reason for hiding this comment

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

closeFormUpload - мы не можем использовать без этой функции
при удалении обработчика мы используем onClickCloseBtnForm внутри closeFormUpload

const onDocumentKeydown = (event) => isEscapeKey(event) && (document.activeElement === inputHashtags || document.activeElement === inputDescription ? event.stopPropagation() : closeFormUpload());// eslint-disable-line

const onClickCloseBtnForm = () => closeFormUpload();// eslint-disable-line

Copy link
Contributor

Choose a reason for hiding this comment

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

Принято не оставлять в коде более одной пустой строки

Copy link
Contributor Author

Choose a reason for hiding this comment

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

оставил две строки только в тех местах, где логическое отделение блоков кода

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправлено


uploadFile.addEventListener('change', onClickFormUpload);

pristine.addValidator(inputHashtags, validateHashtags, getError('tags'), 1, false);
Copy link
Contributor

Choose a reason for hiding this comment

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

Имена полей (tags и description) и значения 1, 2 - это было бы полезно вынести в константы. Предлагаю это обсудить отдельно

Copy link
Contributor Author

Choose a reason for hiding this comment

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

приоритет валидации (1 и 2) убрал, не нашел смысловой нагрузки в нем.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

значения 1 и 2 убрал, они отвечали за приоритет валидации, однако в ТЗ не указан приоритет валидации

Copy link
Contributor Author

Choose a reason for hiding this comment

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

добавил константы, нужно обсудить

js/validation.js Outdated
};

const validateHashtags = (value) => {

Copy link
Contributor

Choose a reason for hiding this comment

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

много пустых строк - разряженный текст сложно читать:

  • пустые строки отделяют функции - перед и после
  • пустую строку часто оставляем перед return
  • можем отделить крупные логические блоки

Copy link
Contributor Author

Choose a reason for hiding this comment

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

поправил

Copy link
Contributor Author

Choose a reason for hiding this comment

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

убрал избыточные пустые строки

js/validation.js Outdated


const validateDescription = (inputText) => {

Copy link
Contributor

Choose a reason for hiding this comment

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

Можем исключить пустую строку перед первым условием в функции

Copy link
Contributor Author

Choose a reason for hiding this comment

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

убрал пустую строку

js/validation.js Outdated
}
];

return rules.every((rule) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Избыточная конструкция. В данном случае она повторяет код другой функции и напрашивается вынесение этого решения в отдельную функцию.

Чтобы такого желания не было:

if (inputText.length > DESCRIPTION_SYMBOLS_MAX) {
  действие
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправил

js/validation.js Outdated
return true;
}

const rules = [
Copy link
Contributor

Choose a reason for hiding this comment

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

Здесь список не требуется

Copy link
Contributor Author

Choose a reason for hiding this comment

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

исправил

js/validation.js Outdated
return true;
}

const inputArray = inputText.split(/\s+/);
Copy link
Contributor

Choose a reason for hiding this comment

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

Неполезно использовать венгерскую нотацию - не добавляем в названия сущностей их тип. Когда задаем вопрос "что это?", ключевым должно оказать название сущности, не тип

Copy link
Contributor Author

Choose a reason for hiding this comment

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

изменил нейминг на inputData

js/validation.js Outdated

return rules.every((rule) => {
const isInvalid = rule.check;
if (isInvalid) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Можем упростить и исключить константу

if (rule.check) {
  ...
  return false;
}
return true;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

упростил и исключил константу

js/validation.js Outdated
error: 'Хэштеги разделяются пробелами.'
},
{
check: inputArray.some((item, num, arr) => arr.includes(item, num + 1)),
Copy link
Contributor

Choose a reason for hiding this comment

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

  • num полезно заменить на i - буквой i именуем индекс
  • arr - можем не использовать аргумент, так как в замыкании есть исходная коллекция

Copy link
Contributor Author

Choose a reason for hiding this comment

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

поправил замечание

@ILokalin ILokalin merged commit d1002f0 into htmlacademy-javascript:master Jun 2, 2025
1 check passed
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