Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,7 @@ <h2 class="success__title">Изображение успешно загруже
<h2 class="data-error__title">Не удалось загрузить данные</h2>
</section>
</template>
<script src="js/functions.js" type="module"></script>
<script src="js/testFunctions.js" type="module"></script>
<script src="js/main.js" type="module"></script>

</body>
</html>
5 changes: 5 additions & 0 deletions js/data.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 49 additions & 0 deletions js/generate-objects.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* eslint-disable no-console */
import { MESSAGES_ARRAY, DESCRIPTION_ARRAY, NAMES } from './data.js';
import { getRandomArrayElement, createRandomRangeInteger, createIdGenerator } from './util.js';
const generateCommentId = createIdGenerator(1, 100000);
const generatePhotoId = createIdGenerator(1, 25);
const generatePhotoNumber = createIdGenerator(1, 25);

const createMessage = () => {
const first = getRandomArrayElement(MESSAGES_ARRAY);
if (createRandomRangeInteger(0, 1) === 0) {
return first;
}
const second = getRandomArrayElement(MESSAGES_ARRAY);
return `${first } ${ second}`;
};

const createComment = () => ({
id: generateCommentId(), //случайное число, не должны повторяться
avatar: `img/avatar-${ createRandomRangeInteger(1,6) }.svg`,//число от 1 до 6 выбирается рандомно

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, 6
Нужно вынести в перечисление

const NumberOfAvatars = {
  MIN: 1,
  MAX: 6
}

message: createMessage(),
name: getRandomArrayElement(NAMES), //массив имён, выбирается рандомно
});

const createCommentsArray = function () {
const commentsArray = [];
const count = createRandomRangeInteger (0, 30);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Магические числа 0 и 30 - нужно вынести в перечисления

for (let i = 0; i <= count - 1; 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.

i < count будет короче

commentsArray[i] = createComment();
}
return commentsArray;
};

const createDescriptionPhoto = function () {
return {
id: generatePhotoId(),//уникальное число от 1 до 25 - целое???
url: `photos/${ generatePhotoNumber() }.jpg`, //адрес картинки photos/{{i}}.jpg, i - случаное и не должно повторяться
description: getRandomArrayElement(DESCRIPTION_ARRAY), //?????
likes: createRandomRangeInteger(15, 200), //число лайков, поставленных фотографии, от 15 до 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.

Магические числа 15, 200

comments: createCommentsArray()//массив объектов комментарий, отсавленных к конкретной фотографии, случайное количество от 0 до 30

};
};

export const createDescriptionsPhotoArray = 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.

Экспорт лучше вынести в самый низ

return Array.from ({length: 25}, createDescriptionPhoto);
};


console.log ('Массив из сгенерированный 25-ти объектов:', JSON.stringify(createDescriptionsPhotoArray(), null, 2));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Это лучше вызывать в main.js, так как именно в main.js мы будем женить эти данные с представлением

3 changes: 3 additions & 0 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* eslint-disable no-console */
import { createDescriptionsPhotoArray } from './generate-objects.js';
console.log ('Генерация 25-ти объектов в массиве:', createDescriptionsPhotoArray());
23 changes: 23 additions & 0 deletions js/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/* eslint-disable no-console */
import './data.js';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Утилиты должны быть чистыми функциями. Импортом с сайд эффектом (то есть импорт без переменной) вообще опасная штука, отлаживать такое очень сложно

export const createRandomRangeInteger = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
export const getRandomArrayElement = (array) => array[createRandomRangeInteger(0, array.length - 1)];
export const createIdGenerator = (min, max) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Убери пожалуйста все экспорты вниз
export { createRandomRangeInteger, getRandomArrayElement, createIdGenerator }

const arrayIds = [];
for (let i = min; i <= max; i++) {
arrayIds.push(i);
}
for (const i of arrayIds) {
const j = createRandomRangeInteger(0,i);
[arrayIds[i], arrayIds[j]] = [arrayIds[j], arrayIds[i]];
}
let currentIndex = 0;
return () => {
if (currentIndex >= arrayIds.length) {
return null;
}
const id = arrayIds[currentIndex];
currentIndex++;
return id;
};
};
Loading