-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
41 lines (33 loc) · 1.28 KB
/
Copy pathscript.js
File metadata and controls
41 lines (33 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
let getRandomProducts = async () => {
let allProducts = [];
let limit = 100;
let skip = 0;
while (true) {
const response = await fetch(`https://dummyjson.com/products?limit=${limit}&skip=${skip}`);
const data = await response.json();
if (data.products.length === 0) {
break;
}
allProducts = allProducts.concat(data.products);
skip += limit;
}
let randomProducts = [];
let usedIndices = new Set();
while (randomProducts.length < 4) {
let randomIndex = Math.floor(Math.random() * allProducts.length);
if (!usedIndices.has(randomIndex)) {
randomProducts.push(allProducts[randomIndex]);
usedIndices.add(randomIndex);
}
}
randomProducts.forEach((product, index) => {
let productCard = document.getElementById(`product${index + 1}`);
if (productCard) {
productCard.querySelector('.product-logo').src = product.thumbnail || '';
productCard.querySelector('.product-name').textContent = product.title || '';
productCard.querySelector('.product-description').textContent = product.description || '';
productCard.querySelector('.product-photo').src = product.images ? product.images[0] : '';
}
});
};
getRandomProducts();