Skip to content

Conversation

@PAVLUXAN
Copy link
Contributor

@PAVLUXAN PAVLUXAN commented Jul 12, 2025

@keksobot keksobot changed the title feat:create functions for validate hashtags Правда или действие Jul 12, 2025
@keksobot
Copy link
Contributor

♻️ Я собрал ваш пулреквест. Посмотреть можно здесь.

keksobot pushed a commit that referenced this pull request Jul 12, 2025
@keksobot
Copy link
Contributor

♻️ Я собрал ваш пулреквест. Посмотреть можно здесь.

keksobot pushed a commit that referenced this pull request Jul 13, 2025
document.addEventListener('keydown', onEscapeKeydown);
};

const onHashTagInput = () => {

Choose a reason for hiding this comment

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

Функции делятся на две категории:

  • действие - выполняет работу с данными
  • предикат (утверждение) - отвечает true/false

Предикаты всегда именуем в форме вопроса - начинается, обычно со слов is или has

Все остальные функции всегда именуем начиная с глагола, который отвечает на вопрос "что сделать?": получить, управлять, добавить, построить, и т.д.

Именование начинающееся с on используется, но обычно в библиотеках и лучше его не применять в проекте. Примеры замен:

handleTagChange
handlePhotoSelect

};

const onHashTagInput = () => {
isHashtagsValid(inputHashtag.value);

Choose a reason for hiding this comment

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

hash и tag - это два слова или одно? Если два, то Tag с большой буквы. Если одно, то надо поправить в других функциях именование

js/util.js Outdated
export {getRandomNumber, getRandomItem};
const isEscapeKey = (evt) => evt.key === 'Escape';

const numDecline = (num, nominative, genetiveSingular, genetivePlural) => {

Choose a reason for hiding this comment

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

Что делает функция? Ожидается глагол основным словом

И опечатка в названии - правильно genitive

@@ -1,5 +1,6 @@
import {photos} from './create-desc.js';
import { openBigPicture } from './render-big-photo.js';
//import { onPhotoSelect } from './img-form-uploader.js';

Choose a reason for hiding this comment

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

Если строка не нужна, не включаем ее в репозиторий

@keksobot
Copy link
Contributor

♻️ Я собрал ваш пулреквест. Посмотреть можно здесь.

keksobot pushed a commit that referenced this pull request Jul 13, 2025
@@ -0,0 +1,49 @@
import {isEscapeKey} from './util.js';
import {error, isHashtagsValid} from './hashtag-validator.js';

Choose a reason for hiding this comment

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

по ТЗ ожидалась валидация тегов и комментария - п.5. задания


let errorMessage = '';

export const error = () => errorMessage;

Choose a reason for hiding this comment

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

именование - ожидается глагол

const MAX_HASHTAGS = 5;
const MAX_SYMBOLS = 20;

let errorMessage = '';

Choose a reason for hiding this comment

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

удобнее реализовать объект с валидируемыми полями: тег и комментарий. Один общий модуль для валидации обоих полей.

@keksobot
Copy link
Contributor

♻️ Я собрал ваш пулреквест. Посмотреть можно здесь.

keksobot pushed a commit that referenced this pull request Jul 14, 2025
@keksobot
Copy link
Contributor

♻️ Я собрал ваш пулреквест. Посмотреть можно здесь.

keksobot pushed a commit that referenced this pull request Jul 15, 2025
MAX_SYMBOLS_COMMENT: 140
};

let getErrorMessage = '';

Choose a reason for hiding this comment

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

Удобнее пользоваться объектами

const errors = {
hashtags: '',
comment: '',
}


let getErrorMessage = '';

export const getError = () => getErrorMessage;

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]

},
{
check:inputArray.some((item) => item.length > settings.MAX_SYMBOLS_HASHTAG),
error:`Максимальная длина одного хештега ${settings.MAX_SYMBOLS_HASHTAG} символов, включая решетку`

Choose a reason for hiding this comment

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

Идеально - вынести все тексты в константы. Не срочно, но полезно реализовать

export {getRandomNumber, getRandomItem};
const isEscapeKey = (evt) => evt.key === 'Escape';

const getCorrectFormWord = (num, nominative, genitiveSingular, genitivePlural) => {

Choose a reason for hiding this comment

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

Если я правильно понимаю, функции мы передаем варианты слов и значение. Функция выбирает слово в соответствии со значением.

Если так, то "выбрать" в качестве глагола. Обычно это связываем с "окончанием" и можем уточнить, что является основой выбора. Варианты:

  • selectPlural
  • selectPluralByCount
  • selectWordByCount

return true;
}

const rule = {
Copy link

@ILokalin ILokalin Jul 17, 2025

Choose a reason for hiding this comment

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

Избыточно для этого валидатора. Просто условие сделать и если нет, сохранить текст ошибки


const rules = [
{
check:inputArray.some((item) => item === '#'),

Choose a reason for hiding this comment

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

Было бы хорошим вариантом все check реализовать в виде функций и запускать их при проверке. Это исключит запуск всех кейсов и исключений

return true;
}

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

Choose a reason for hiding this comment

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

не используем слово array и object в именовании

"данные", "разделенный инпут", "теги" др.

В данном случае можно, как конкретизировать название (все же это теги), можно обобщить

@keksobot keksobot merged commit 253c6a7 into htmlacademy-javascript:master Jul 17, 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.

3 participants