Skip to content

Commit cdec8a3

Browse files
authored
Merge pull request #3 from zarram89/module4-task1
2 parents 4393a22 + dbcdad8 commit cdec8a3

2 files changed

Lines changed: 126 additions & 8 deletions

File tree

index.html

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<!DOCTYPE html>
22
<html lang="ru">
3+
34
<head>
45
<meta charset="utf-8">
56
<meta name="viewport" content="width=device-width,initial-scale=1">
@@ -162,7 +163,7 @@ <h2 class="big-picture__title visually-hidden">Просмотр фотогра
162163
</li>
163164
<li class="social__comment">
164165
<img class="social__picture" src="img/avatar-3.svg" alt="Аватар комментатора фотографии" width="35" height="35">
165-
<p class="social__text">Да это фоташоп!!!!!!!!</p>
166+
<p class="social__text">Да это фоташоп!!!!!!!!</p>
166167
</li>
167168
</ul>
168169

@@ -227,12 +228,13 @@ <h2 class="success__title">Изображение успешно загруже
227228
</section>
228229
</template>
229230

230-
<!-- Сообщение с ошибкой загрузки изображений от других пользователей -->
231-
<template id="data-error">
232-
<section class="data-error">
233-
<h2 class="data-error__title">Не удалось загрузить данные</h2>
234-
</section>
235-
</template>
236-
231+
<!-- Сообщение с ошибкой загрузки изображений от других пользователей -->
232+
<template id="data-error">
233+
<section class="data-error">
234+
<h2 class="data-error__title">Не удалось загрузить данные</h2>
235+
</section>
236+
</template>
237+
<script src="js/main.js" type="module"></script>
237238
</body>
239+
238240
</html>

js/main.js

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
const MESSAGES = [
2+
'Всё отлично!',
3+
'В целом всё неплохо. Но не всё.',
4+
'Когда вы делаете фотографию, хорошо бы убирать палец из кадра. В конце-концов это просто непрофессионально.',
5+
'Моя бабушка случайно чихнула с фотоаппаратом в руках и у неё получилась фотография лучше.',
6+
'Я поскользнулся на банановой кожуре и уронил фотоаппарат на кота и у меня получилась фотография лучше.',
7+
'Лица у людей на фотке перекошены, как-будто их избивают. Как можно было поймать такой неудачный момент?!',
8+
];
9+
const DESCRIPTIONS = [
10+
'Летний чил на югах. #тай #отдых #лето #чил #travel #travelgram #summergram #chill',
11+
'Тестим новую камеру! #camera #test #new #newcameratest #pic #photo #instaphoto',
12+
'Затусили с друзьями на море #laptevsea #north #northeastpassage',
13+
'Как же круто тут кормят #food #foodgram #instafood #delicious #yummy',
14+
'Отдыхаем... #chill #relax #group #photo',
15+
'Цените каждое мгновенье. Цените тех, кто рядом с вами и отгоняйте все сомненья. Не обижайте всех словами......',
16+
'Вот это тачка! #wow #car #carwow #drive',
17+
'#fun #party #cool #young',
18+
'Господи, это такая милота, я сейчас умру от нежности, у меня закшалил мимимиметр',
19+
'Хорошо, когда в жизни есть #друзья, которые вместе со мной могут зайти в #барнарубинштейна и бахнуть #пивка',
20+
'Норм',
21+
];
22+
const NAMES = ['Николай', 'Аким', 'Ким', 'Харитон', 'Тимур', 'Степан'];
23+
const PICTURES_LENGTH = 25;
24+
25+
const CONFIG = {
26+
likes: { min: 15, max: 200 },
27+
comments: { min: 0, max: 30 },
28+
avatar: { min: 1, max: 6 },
29+
messages: { min: 1, max: 2 },
30+
};
31+
32+
const getRandomInteger = (min, max) => {
33+
if (min === undefined || max === undefined) {
34+
throw new TypeError('Both min and max must be provided');
35+
}
36+
37+
if (typeof min !== 'number' || typeof max !== 'number') {
38+
throw new TypeError('min and max must be numbers');
39+
}
40+
41+
if (!Number.isFinite(min) || !Number.isFinite(max)) {
42+
throw new TypeError('min and max must be finite numbers');
43+
}
44+
45+
const lower = Math.ceil(Math.min(min, max));
46+
const upper = Math.floor(Math.max(min, max));
47+
48+
if (lower > upper) {
49+
throw new RangeError('Invalid range');
50+
}
51+
52+
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
53+
};
54+
55+
const getRandomItem = (items) => {
56+
if (!Array.isArray(items) || items.length === 0) {
57+
throw new TypeError('items must be a non-empty array');
58+
}
59+
60+
return items[getRandomInteger(0, items.length - 1)];
61+
};
62+
63+
const createIdGenerator = () => {
64+
let lastGeneratedId = 0;
65+
66+
return () => {
67+
lastGeneratedId += 1;
68+
return lastGeneratedId;
69+
};
70+
};
71+
72+
const pictureIdGenerator = createIdGenerator();
73+
const commentIdGenerator = createIdGenerator();
74+
75+
const getRandomAvatar = () =>
76+
`img/avatar-${getRandomInteger(CONFIG.avatar.min, CONFIG.avatar.max)}.svg`;
77+
78+
const createMessage = () =>
79+
Array.from(
80+
{ length: getRandomInteger(CONFIG.messages.min, CONFIG.messages.max) },
81+
() => getRandomItem(MESSAGES)
82+
).join(' ');
83+
84+
const createComment = () => ({
85+
id: commentIdGenerator(),
86+
avatar: getRandomAvatar(),
87+
message: createMessage(),
88+
name: getRandomItem(NAMES),
89+
});
90+
91+
const getComments = () =>
92+
Array.from(
93+
{ length: getRandomInteger(CONFIG.comments.min, CONFIG.comments.max) },
94+
createComment
95+
);
96+
97+
const createPicture = () => {
98+
const id = pictureIdGenerator();
99+
100+
return {
101+
id,
102+
url: `photos/${id}.jpg`,
103+
description: getRandomItem(DESCRIPTIONS),
104+
likes: getRandomInteger(CONFIG.likes.min, CONFIG.likes.max),
105+
comments: getComments(),
106+
};
107+
};
108+
109+
const getPictures = () =>
110+
Array.from(
111+
{ length: PICTURES_LENGTH },
112+
(_, index) => createPicture(index)
113+
);
114+
115+
// eslint-disable-next-line no-console
116+
console.log(getPictures());

0 commit comments

Comments
 (0)